首页 > 解决方案 > 雄辩中 Records.records.record.column 的 laravel 总和

问题描述

这是关系

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

这是模型类

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

我想要实现的是获得当前交易总价格(很多)

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

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

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

标签: laraveleloquenteloquent-relationship

解决方案


我终于找到了一个更好的方法来收集减少而不是 foreach

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

推荐阅读