如何使两个值的条件具有laravel雄辩的'when',而不是if elseif

如何使两个值的条件具有laravel雄辩的'when',而不是if elseif,laravel,if-statement,eloquent,Laravel,If Statement,Eloquent,如何将其转换为: if(isset($from) && isset($to)) { $query->where('column1', $from)->where('column2', $to); } elseif(isset($from)) { $query->where('column1', $from); } elseif(isset($to)) { $query->where('column1', $to); } 在Lara

如何将其转换为:

if(isset($from) && isset($to))
{
    $query->where('column1', $from)->where('column2', $to);
}
elseif(isset($from))
{
    $query->where('column1', $from);
}
elseif(isset($to))
{
    $query->where('column1', $to);
}
在Laravel中使用
时执行类似操作:

...
->when(isset($from) && isset($to), function($query) use ($from, $to)
{
    $query->where('column1', $from)->where('column2', $to);
})
->elseWhen(isset($from), function($query) use ($from)
{
    $query->where('column1', $from)->where('column2', $from);
})
->elseWhen(isset($to), function($query) use ($to)
{
    $query->where('column2', $to);
});

谢谢

您可以在以下情况下使用

...
->when(isset($from), function($query) use ($from)
{
    return $query->where('column1', $from);
})
->when(isset($to), function($query) use ($to)
{
    return $query->where('column2', $to);
});

在这种情况下,如果设置了两个值,那么您将得到与第一个条件完全相同的结果:)

您可以使用
或where
,例如

 $query->where('column1', $from)->orWhere('column2', $to);

这将替换上面的所有代码(我指的是if)。我相信这是一个优化的查询,因为当
时,您不需要使用

为什么要使用第二个,如果第一个已经解决了您的问题?因为可能用户只从
参数设置了
。这是对的,但我需要在另一个查询中使用这些变量,当,获取数据并将获取的数据用于下一个查询。您可以在其他查询中使用它,但之后应返回查询生成器!是的,谢谢:))