我怎样才能在Laravel中查询构建Where IF条件

时间:2016-09-06 16:11:07

标签: mysql laravel laravel-5.2

我在我的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();

3 个答案:

答案 0 :(得分:2)

我不知道这是不是正确的方法,但是我使用了像@vijaykuma所说的whereRaw。

按照查询

new Date(Date.now() + minutes*60*1000).toLocaleString()

答案 1 :(得分: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();

希望有帮助=)

答案 2 :(得分: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

  

如果(表达式1,表达式2,表达式3)

     

如果expr1为TRUE,则IF()返回expr2。否则,它返回expr3。

相关问题