Im building a simple buy and sell application with Laravel 5.1. Each Buy Model has many BuyDetail which stores bought item quantity and buy_price. I have implement the relationship between table on the 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计算总价的最佳方法是什么?
for now i just implement it like this:
@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