2016-09-06 62 views
2

我在我的MySQL編輯器中建立一個查詢,但現在我想在查詢生成器SQL在Laravel 5下面轉換這個SQL,有人可以幫助我嗎?我搜索了很多關於Laravel的IF條件,但沒有找到的地方。我如何查詢生成在哪裏如果條件在Laravel

select * 
from eventos 
where inicio = '2016-09-06 09:41' 
and recorrencia = 0 
or recorrencia = 1 
and 
(
    if (recorrencia_tipo = 'semanal', recorrencia_intervalo, 7) LIKE concat('%', weekday('2016-09-06 00:00:00'), '%') 
     or 
    if(recorrencia_tipo = 'mensal', recorrencia_intervalo, 0) = day('2016-09-06 09:41') 
     or 
    (
     if (recorrencia_tipo = 'anual', substring_index(recorrencia_intervalo, '/', 1), 0) = DAY('2016-09-06 09:41') 
      or 
     if (recorrencia_tipo = 'anual', substring_index(recorrencia_intervalo, '/', -1), 0) = MONTH('2016-09-06 09:41') 
    ) 
) 

我建造直到在Laravel

Evento::where('inicio', '2016-09-06 09:41') 
      ->where('recorrencia', 0) 
      ->orWhere('recorrencia', 1) 
      ->where('recorrencia_tipo', function ($query) { 
      })->get(); 
+0

爲什麼不嘗試原始查詢一次? – vijaykumar

+0

感謝隊友,你的回答對我很有幫助= D –

回答

0

我不知道這是正確的做法,但我把它用whereRaw像@vijaykuma說沒有。

按照查詢

$eventos = Evento::where('inicio', $data) 
      ->where('recorrencia', 0) 
      ->orWhere('recorrencia', 1) 
      ->whereRaw(" 
       IF (recorrencia_tipo = 'semanal', recorrencia_intervalo, 7) LIKE concat('%', weekday('{$data}'), '%') 
        OR 
       IF (recorrencia_tipo = 'mensal', recorrencia_intervalo, 0) = DAY('{$data}') 
        OR 
       (
        IF (recorrencia_tipo = 'anual', substring_index(recorrencia_intervalo, '/', 1), 0) = DAY('{$data}') 
         AND 
        IF (recorrencia_tipo = 'anual', substring_index(recorrencia_intervalo, '/', -1), 0) = MONTH('{$data}') 
       ) 
      ")->get(); 
0

試試這個:

Evento::where('inicio', '2016-09-06 09:41') 
     ->where('recorrencia', 0) 
     ->orWhere('recorrencia', 1) 
     ->where('recorrencia_tipo', function ($query) { 
      if(condition){ 
      $query->select('column')->from('table')->where('where clause'); 
      } 
      else{ 
      $query->select('column')->from('table')->where('where clause'); 
      } 
     }) 
     ->get(); 

希望它可以幫助=)

0

如果你已經落在這裏試圖使IF工作作爲SELECT的一部分,這可能有所幫助:

$query = DB::table('mytable') 
    ->select(DB::raw('id,title,IF(some_column = 1, some_column,null) as some_column')) 
    ->get(); 

牢記: https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html

IF(表達式1,表達式2,表達式3)

如果表達式1爲真,IF()返回expr2的。否則,它返回expr3。