2017-03-01 9 views
1

の使用合計メソッドのは、私はこれらの2つのモデルがあるとしましょう:Laravelクエリビルダ - 生成された属性

注文モデル:

  • (完全不完全、)ID
  • 状態

アイテムモデル:

  • ID
  • is_worthy
  • をORDER_ID。

/** 
* 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'); 
関連する問題