Laravel Eloquent:计算总价的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31421666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent: Best Way to Calculate Total Price
提问by Wendy Adi
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.
我用 Laravel 5.1 构建了一个简单的买卖应用程序。每个 Buy Model 都有许多 BuyDetail,用于存储购买的商品数量和buy_price。我已经在模型上实现了表之间的关系。
class Buy extends Model
{
#Eloquent relationships
public function supplier()
{
return $this->belongsTo('App\Supplier');
}
public function buyDetails()
{
return $this->hasMany('App\BuyDetail');
}
}
I'd like to calculate the total price for each Buy. What is the best way to calculate the total price using Eloquent ORM?
我想计算每次购买的总价。使用 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
采纳答案by jedrzej.kurylo
This can be done in (at least) 2 ways.
这可以通过(至少)两种方式完成。
Using pure Eloquent model logic:
使用纯 Eloquent 模型逻辑:
class Buy extends Model
{
public function getTotalPrice() {
return $this->buyDetails->sum(function($buyDetail) {
return $buyDetail->quantity * $buyDetail->price;
});
}
}
The only issue here is that it needs to fetch all buy details from the database but this is something you need to fetch anyway to display details in the view.
这里唯一的问题是它需要从数据库中获取所有购买详细信息,但无论如何您都需要获取这些内容以在视图中显示详细信息。
If you wanted to avoid fetching the relation from the database you could build the query manually:
如果您想避免从数据库中获取关系,您可以手动构建查询:
class Buy extends Model
{
public function getTotalPrice() {
return $this->buyDetails()->sum(DB::raw('quantity * price'));
}
}
回答by Martin Bean
I realise an answer's already been accepted, but just thought I'd add my own detailing another approach.
我意识到一个答案已经被接受,但只是想我会添加我自己的详细说明另一种方法。
Personally, I like to put “aggregate” methods like these on custom collection classes. So if I have a Buy
model that can have many BuyDetail
models, then I would put a getTotal()
method on my BuyDetailCollection
method like this:
就我个人而言,我喜欢将这些“聚合”方法放在自定义集合类中。因此,如果我有一个Buy
可以包含多个BuyDetail
模型的模型,那么我会getTotal()
在我的BuyDetailCollection
方法中放置一个方法,如下所示:
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
class BuyDetailCollection extends EloquentCollection
{
public function getTotal()
{
return $this->items->sum(function ($detail) {
return $detail->price * $detail->quantity;
});
}
}
I can then add this to the BuyDetail
model:
然后我可以将其添加到BuyDetail
模型中:
class BuyDetail extends Model
{
public function newCollection(array $models = [])
{
return new BuyDetailCollection($models);
}
}
And use my getTotal()
method where ever I need to now:
并getTotal()
在我现在需要的地方使用我的方法:
$buy = Buy::with('buyDetails')->find($id);
$total = $buy->buyDetails->getTotal();