laravel 7 从 eloquent 关系列中获取总和

laravel 7 Get Sum From eloquent relation column

 $user = User::with(['affiliateCode','rewardPoints','orders'=>function($query){
        $query->where('order_status_id','!=',1);
    }])
    ->withCount(['orders'=>function($q){
        $q->where('order_status_id','!=',1);   
    }])
    ->where('id',$userId)->first();

上面的代码工作正常..我还想 return sum 所有 amount 来自 orders table where order_status_id !=1 有了这个回应..

我试过 withSum() 但自从 laravel 7 之后就没用了, 任何人都可以帮助 return 求和吗?谢谢

您可以像这样使用带有回调的 withCount 方法。

$user = User::with(['affiliateCode','rewardPoints','orders'=>function($query){
        $query->where('order_status_id','!=',1);
    }])
    ->withCount(['orders'=>function($q){
        $q->where('order_status_id','!=',1);   
    }])
    ->withCount(['orders as orders_amount'=>function($q){
        $q->where('order_status_id','!=',1)->select(DB::raw('sum(amount)'));   
    }])
    ->where('id',$userId)->first();