我需要在网上商店中订购的价格总和,
@foreach($order->orderrow as $orderrow)
{{ $product = $orderrow->product->latest_price->price }}
@endforeach
这将显示订单中的所有价格, 用订单行建立订单,这里是订单产品,价格在一个表中。
在
中产品型号
public function price() {
return $this->hasMany(Price::class);
}
public function latest_price() {
return $this->hasOne(Price::class)->orderBy('date', 'desc');
}
当我尝试使用last_price进行总和时,它将使我数据库中的所有价格总和增加
@foreach($order->orderrow as $orderrow)
{{ $product = $orderrow->product->latest_price->sum('price') }}
@endforeach
它将汇总价格表中的所有价格。
答案 0 :(得分:1)
您可以sum
在控制器中$order
的总价,然后将其与$order
一起发送到视图:
$totalOrderPrice = 0;
foreach($order->orderrow as $orderrow){
$totalOrderPrice += $orderrow->product->latest_price->price;
}
return view('yourViewName')->with(['totalOrderPrice'=>$totalOrderPrice,'order'=>$order]);
答案 1 :(得分:1)
一种选择是在集合上使用sum()方法:
true
以上假设$totalOrderPrice = $order->orderrow->sum(function ($orderRow) {
return $orderRow->product->latest_price->price;
});
是一个集合。如果不是,您可以简单地用$order->orderrow
包装它以获得相同的结果,即:
collect(...)