Laravel查询生成器-在生成的属性上使用sum方法 [英] Laravel Query Builder - Use sum method on a generated attribute
本文介绍了Laravel查询生成器-在生成的属性上使用sum方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下两种型号:
Let's say I have these 2 models:
订单模型:
- id
- 状态(不完整,完整)
项目模型:
- id
- order_id
- 类型
- 值得.
.
/**
* Returns the item's price according to its worthy
*/
public function getPriceAttribute()
{
return $this->is_worthy ? 100 : 10; // $
}
到目前为止一切都很好.
So far so good.
现在,我要总结完整订单的价格.所以我正在这样做:
Now I want to summarize the price of the complete orders. So I'm doing this:
App\Item::whereHas('order', function ($query) {
$query->where('state', 'complete');
})->sum('price')
但是问题是,我的items
表中没有列price
.因为price
属性是在模型中生成的.
But the thing is, that I don't have in my items
table the column price
. Because the price
attribute is generated in the Model.
所以我的问题是,如何汇总完整订单的价格?
So my question is, how can I summarize price of the complete orders?
推荐答案
有两种方法可以做到这一点:
There are 2 ways to do this:
1.让PHP完成所有工作
$items = App\Item::whereHas('order', function ($query) {
$query->where('state', 'complete');
})->get();
$sum = $items->sum(function($item) {
return $item->price;
});
// In Laravel 5.4, you can replace the last line with $sum = $items->sum->price;
2.让SQL完成所有工作
$items = App\Item::whereHas('order', function ($query) {
$query->where('state', 'complete');
})->select('*', DB::raw('IF(is_worthy, 100, 10) as price'))->sum('price');
这篇关于Laravel查询生成器-在生成的属性上使用sum方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文