Laravel查询生成器 - 对生成的属性使用sum方法

Eli*_*hen 1 php mysql laravel eloquent laravel-query-builder

假设我有这两种型号:

订单型号:

  • ID
  • 国家(不完整,完整)

商品型号:

  • ID
  • ORDER_ID
  • 类型
  • is_worthy.

.

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

到现在为止还挺好.

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

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

但问题是,我的items表中没有列price.因为该price属性是在模型中生成的.

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

Par*_*ras 6

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

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;
Run Code Online (Sandbox Code Playgroud)

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');
Run Code Online (Sandbox Code Playgroud)