2017-03-01 80 views
1

比方說,我有這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

回答

4

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