2014-10-08 104 views
2

用雄辯我有以下查詢寫着:Laravel多WHERE()運算符優先級

Contact::select(DB::raw("DATE_FORMAT(DATE(`created_at`),'%b %d') as date")) 
           ->addSelect(DB::raw("`created_at`")) 
           ->addSelect(DB::raw("COUNT(*) as `count`")) 
           ->where('created_at', '>', $date) 
           ->ofType($type) 
           ->groupBy('date') 
           ->orderBy('created_at', 'ASC') 
           ->lists('count', 'date'); 

你可以看到它採用了查詢範圍方法ofType()這裏是一個方法,它只是增加了一堆額外的where子句中到查詢:

return $query->where('list_name', '=', 'Apples') 
      ->orWhere('list_name', '=', 'Oranges') 
      ->orWhere('list_name', '=', 'Pears') 
      ->orWhere('list_name', '=', 'Plums') 
      ->orWhere('list_name', '=', 'Blueberries'); 

這最終將導致以下實際的SQL查詢:

SELECT DATE_FORMAT(DATE(`created_at`),'%b %d') as date,`created_at`, COUNT(*) as `count` 
FROM `contacts` 
WHERE `created_at` > '2014-10-02 00:00:00' 
AND `list_name` = 'Apples' 
OR `list_name` = 'Oranges' 
OR `list_name` = 'Pears' 
OR `list_name` = 'Plums' 
OR `list_name` = 'Blueberries' 
GROUP BY `date` 
ORDER BY `created_at` ASC 

問題是,由於運營商的優先權,在OR條款開始時,錯過了WHERE created_at>'2014-10-02 00:00:00'條款。我需要後的第一和括號包裹所有條款,像這樣:

SELECT DATE_FORMAT(DATE(`created_at`),'%b %d') as date,`created_at`, COUNT(*) as `count` 
    FROM `contacts` 
    WHERE `created_at` > '2014-10-02 00:00:00' 
    AND 
    (`list_name` = 'Apples' 
    OR `list_name` = 'Oranges' 
    OR `list_name` = 'Pears' 
    OR `list_name` = 'Plums' 
    OR `list_name` = 'Blueberries') 
    GROUP BY `date` 
    ORDER BY `created_at` ASC 

所以,我的問題是,我將如何實現這一目標用雄辯的查詢生成器。謝謝。

+0

您是否在尋找高級女性?我認爲這可能會幫助您實現您的查詢:http://laravel.com/docs/4.2/queries#advanced-wheres – 2014-10-08 10:25:03

+0

謝謝,這工作完美。 – 2014-10-08 10:45:59

回答

3

感謝mOrsa我已經想通了,通過改變我的查詢範圍的方法來充分利用先進的優勢在哪裏:

return $query->where(function($query){ 

      $query->orWhere('list_name', '=', 'Apples') 
       ->orWhere('list_name', '=', 'Oranges') 
       ->orWhere('list_name', '=', 'Pears') 
       ->orWhere('list_name', '=', 'Plums') 
       ->orWhere('list_name', '=', 'Blueberries'); 
     }); 

我獲得所需的SQL。

+0

我很高興它解決了!快樂的編碼! – 2014-10-09 14:57:53