laravel - 雄辩中 Records.records.record.column 的 laravel 总和
问题描述
这是关系
- 交易
hasMany
车 - 购物车
belongsTo
产品 - 产品
->
价格
这是模型类
//# 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;
}
如何用雄辩的代码做到这一点谢谢
解决方案
我终于找到了一个更好的方法来收集减少而不是 foreach
$totalPrice = $transactions->reduce(function($carry, $current){
return $carry + $current->getCarts->sum('getProduct.price');
},0);
推荐阅读
- twitter-bootstrap - Vue少加载css“无法读取未定义的属性'分母'”
- c# - 如何使用 C# 将 CSV 文件转换为 Parquet
- html - 使用 Nginx 在 Linux 中的静态文件
- mysql - 在 Centos7 上启动时出现 MySQL 5.7 错误
- javascript - 如何避免在 for 循环完成之前调用 .map 函数?
- c++ - 数组只是一个包含许多数据的变量吗?
- python - 正则表达式查找列中有多少单词以元音开头并且有超过 5 个字母
- php - post_meta 值上的 WordPress OrderBY
- azure - 匹配所有内容的 Azure 存储表 powershell customfilter
- datatable - 数据表 - 相同列中的按钮、长度和搜索