Laravel Eloquent:计算总价的最佳方法
2022-08-30 22:11:19
我正在用Laravel 5.1构建一个简单的买卖应用程序。每个购买模型都有许多购买详细信息,其中存储购买的项目数量和buy_price。我已经在模型上实现了表之间的关系。
class Buy extends Model
{
#Eloquent relationships
public function supplier()
{
return $this->belongsTo('App\Supplier');
}
public function buyDetails()
{
return $this->hasMany('App\BuyDetail');
}
}
我想计算每次购买的总价。使用Eloquent ORM计算总价的最佳方法是什么?
现在我只是像这样实现它:
@foreach($buys as $key => $value)
<?php
$total = 0;
?>
@foreach($value->buyDetails as $k => $bD)
<?php
$total += ($bD['buy_price']*$bD['qty']);
?>
@endforeach
<tr>
<td>{{$value->ref_number}}</td>
<td>{{$value->suplier->name}}</td>
<td>{{$value->created_at}}</td>
<td>{{$value->buyDetails->count()}}</td>
<td>{{$total}}</td>
<td>
<a href="" class="btn btn-default btn-sm" title="show">Detail</a>
<a href="" class="btn btn-primary btn-sm" title="edit">Edit</a>
<a href="" class="btn btn-danger btn-sm" title="delete">Delete</a>
</td>
</tr>
@endforeach