繁体   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