簡體   English   中英

我怎樣才能在Laravel中查詢構建Where IF條件

[英]How can i query build Where IF condition in Laravel

我在MySQL編輯器中構建了一個查詢,但現在我想在Laravel 5中的查詢構建器SQL中轉換下面的SQL,有人可以幫助我嗎? 我搜索了很多關於Laravel中的Where IF條件,但沒有找到。

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

我不知道這是不是正確的方法,但是我使用了像@vijaykuma所說的whereRaw。

按照查詢

$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();

嘗試這個:

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

希望它有幫助=)

如果你已經在這里試圖讓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)

如果expr1為TRUE,則IF()返回expr2。 否則,它返回expr3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM