雄辩的Record.records.record.column laravel总和

时间:2019-02-24 07:02:03

标签: laravel eloquent eloquent--relationship

这是关系

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

这是Model类

//# 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 (很多)

我现在所做的仍然是每次交易都进行迭代,并将价格加到$total

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

如何用雄辩的代码做到这一点 谢谢

2 个答案:

答案 0 :(得分:0)

我认为这应该可行:

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');
    }

}

答案 1 :(得分:0)

我终于找到了一个更好的方法,用collection reduce代替foreach

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