laravel eloquent 中 Records.records.record.column 的总和

laravel sum of Records.records.record.column in eloquent

这是关系

  1. 交易hasMany购物车
  2. 购物车belongsTo 产品
  3. 产品->价格

这是模型class

//# TransactionModel
public function getCarts(){
    return $this->hasMany(CartModel::class, 'transaction_id','id');
}
//# CartModel
public function getProduct(){
    return $this->belongsTo(ProductModel::class,'product_id','id');
}

我想实现的是获取当前交易的总价s(many)

我现在做的仍然是每次交易迭代并在 $total

中对价格求和
 Class TransactionModel{
 public static function getTotalPrice($transactions){
    $total = 0;
    foreach($transactions as $transaction){
            $total += $transaction->getCarts->sum('getProduct.price');
    }
    return $total;
 }

如何在 eloquent 代码中做到这一点 谢谢

我认为这应该可行:

Class TransactionModel{

    public function getTotalPrice(){

        return $this->getCarts()->withCount([
            'getProduct' => function($q){ 
                return $q->select(DB::raw("SUM(price) as price_sum")); 
            }
        ])->get()->sum('getProduct_count');
    }

}

我终于找到了一个更好的方法,使用 collection reduce 而不是 foreach

 $totalPrice = $transactions->reduce(function($carry, $current){
                    return $carry + $current->getCarts->sum('getProduct.price');
               },0);