Php Laravel belongsTo查询

Php Laravel belongsTo查询,php,laravel,Php,Laravel,对不起,我不能用一个简单的问题来描述我的问题!所以我要把它写下来以便更好的解释 我有两张桌子 订单表: 销售表: 销售模式 我只需要获得成功订单的总金额 // get profits // this gives me = $50 $profits = Sales::where('user_id',Auth::user()->id)->sum('amount') // trying to do something like .. $profits = Sales::where(

对不起,我不能用一个简单的问题来描述我的问题!所以我要把它写下来以便更好的解释

我有两张桌子

订单表: 销售表: 销售模式 我只需要获得成功订单的总金额

// 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)
嗯,有什么帮助吗

查询

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

})->sum('amount');
用法


调用变量
$total

嗨,拉斐尔,谢谢你,但这不起作用,我只需要获得具有“成功”状态的订单的总数,而不是所有订单的总数。。where('status','success'),那么,我可以把这个条件放在哪里呢?是的!真管用!非常感谢Rafael,非常感谢你抽出时间。。只有一件事,如果你能在sum()上加一个值,因为如果没有一个值,它会给我一个错误。。只需将sum()改为sum('amount'),您就完全忘记了添加它。。再次感谢你,伙计!:)
class Sales extends Eloquent
{
    public function parentorder()
    {
        return $this->belongsTo('Order', 'order_id');
    }
}
// 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)
$total = Sale::whereHas('orders', function($q)
{
    $q->where('status', '=', 'success');

})->sum('amount');