【问题标题】:laravel sum of Records.records.record.column in eloquent雄辩中 Records.records.record.column 的 laravel 总和
【发布时间】:2019-07-17 20:58:02
【问题描述】:

这是关系

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

这里是模型类

//# 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;
 }

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

【问题讨论】:

  • 应该是$transaction->getCarts->product->sum('price')
  • @Iftikharuddin 这就是我所做的,只得到current transation。我们想要达到的是总价many transaction(S)
  • 你使用的是什么版本的 Laravel?另外,请您出示所有 3 种型号的代码。
  • 你能用模型关系更新你的问题吗? getcarts 是做什么的?
  • @RossWilson 已更新。

标签: laravel eloquent eloquent-relationship


【解决方案1】:

我认为这应该可行:

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

}

【讨论】:

  • $this 在静态函数中?
  • 啊谢谢@faizan.sh 我忘了删除静态词,谢谢:) 更新了我的答案
  • 感谢您的回答,但我们想要实现的是许多transaction(S) 的总价,请参阅我的问题第一个字是Records。 $this 表示1 record
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2019-02-13
    • 2018-05-12
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多