gpt4 book ai didi

php - Laravel Query Builder - 在生成的属性上使用 sum 方法

转载 作者:行者123 更新时间:2023-11-29 04:05:42 33 4
gpt4 key购买 nike

假设我有这两个模型:

订购型号:

  • 编号
  • 状态(不完整,完整)

元素型号:

  • 编号
  • 订单编号
  • 输入
  • 值得。

.

/**
* Returns the item's price according to its worthy
*/
public function getPriceAttribute()
{
return $this->is_worthy ? 100 : 10; // $
}

到目前为止一切顺利。

现在我想总结一下完整订单的价格。所以我这样做:

App\Item::whereHas('order', function ($query) {
$query->where('state', 'complete');
})->sum('price')

但问题是,我的 items 表中没有 price 列。因为 price 属性是在 Model 中生成的。

所以我的问题是,如何汇总完整订单的价格?

最佳答案

有两种方法可以做到这一点:

<强>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');

关于php - Laravel Query Builder - 在生成的属性上使用 sum 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42537560/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com