Laravel属于查询

时间:2015-01-16 03:15:38

标签: php laravel

抱歉,我的活动无法用简单的问题描述我的问题!所以我要把它写下来以便更好地解释。

我有2张桌子..

订单表:

id - status  
100 - success  
200 - pending  

销售表:

id - order_id - user_id - amount 
1  - 100 - 5 - $20
2  - 200 - 5 - $30 

销售模式

class Sales extends Eloquent
{
    public function parentorder()
    {
        return $this->belongsTo('Order', 'order_id');
    }
}

我只需要获得SUCESS订单的总金额

// get profits 
// this gives me = $50 
$profits = Sales::where('user_id',Auth::user()->id)->sum('amount')

// trying to do something like .. 
$profits = Sales::where('user_id',Auth::user()->id)->where('parentorder.status','Success')->sum('amount');
// so I get the correct total which is $20 (for the success order id=100)
嗯,嗯,有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

<强>查询

$total = Sale::whereHas('orders', function($q)
{
    $q->where('status', '=', 'success');

})->sum('amount');

<强>用法

调用变量$total