在滔滔不绝的laravel记录中的Records.records.record.column

问题描述 投票:0回答:2

这是关系

  1. 交易hasMany推车
  2. 购物车belongsTo产品
  3. product->price

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

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

我现在所做的仍然是每次交易迭代,并在qazxsw poi中总结价格

$total

如何以雄辩的代码谢谢

laravel eloquent eloquent--relationship
2个回答
0
投票

我认为这应该工作:

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

0
投票

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

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

}
© www.soinside.com 2019 - 2024. All rights reserved.