Laravel belongsTo查询

Laravel belongsTo query

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

我有 2 tables ..

订单table:

id - status  
100 - success  
200 - pending  

销售额table:

id - order_id - user_id - amount 
1  - 100 - 5 - 
2  - 200 - 5 -  

销售模式

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

我只需要获取成功订单的总金额

// get profits 
// this gives me =  
$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  (for the success order id=100)

嗯,有什么帮助吗?

查询

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

})->sum('amount');

用法

调用变量$total