我正在用Laravel 5.1构建一个简单的买卖应用程序。每个购买模型都有许多BuyDetail,它存储购买的商品数量和buy_price。我已经在Model上实现了表之间的关系。
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