Laravel查询生成器 - 在生成的属性用途和方法

问题描述:

比方说,我有这2种型号:Laravel查询生成器 - 在生成的属性用途和方法

订货型号:

  • ID
  • 状态(未完成,完成)

项目型号:

  • ID
  • ORDER_ID
  • 类型
  • is_worthy。

/** 
* 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属性是在模型中生成的。

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

+0

不Laravel有一个whereType?什么是错误信息? –

+0

@FatimahSanni Laravel拥有动态的方法,如whereXyz(xyz是表的列名) – Paras

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

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