【发布时间】:2019-07-17 20:58:02
【问题描述】:
这是关系
- 交易
hasMany购物车 - 购物车
belongsTo产品 - 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