im building simple buy , sell application laravel 5.1. each buy model has many buydetail stores bought item quantity , buy_price. have implement relationship between table on model.
class buy extends model { #eloquent relationships public function supplier() { return $this->belongsto('app\supplier'); } public function buydetails() { return $this->hasmany('app\buydetail'); } } i'd calculate total price each buy. best way calculate total price using eloquent orm?
for implement this:
@foreach($buys $key => $value) <?php $total = 0; ?> @foreach($value->buydetails $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
this can done in (at least) 2 ways.
using pure eloquent model logic:
class buy extends model { public function gettotalprice() { return $this->buydetails->sum(function($buydetail) { return $buydetail->quantity * $buydetail->price; }); } } the issue here needs fetch buy details database need fetch anyway display details in view.
if wanted avoid fetching relation database build query manually:
class buy extends model { public function gettotalprice() { return $this->buydetails()->sum(db::raw('quantity * price')); } }
Comments
Post a Comment