带有 if/else 运算符的 Laravel 查询

时间:2021-02-07 23:39:13

标签: laravel

有没有类似下面例子的用法?

//Let's say there is $data from the user. Can I shape the query based on this value?

if($data==1{
  $q->whereDate('start_date', '<=', '2021-01-01');
  
}else if($data==0){
  $q->whereDate('end_date', '<=', '2021-02-02');
}

1 个答案:

答案 0 :(得分:0)

您可能正在寻找conditional clauses

$q->when(1==1, function ($query) {
    $query->whereDate('start_date', '<=', '2021-01-01');
}, function ($query) {
    $query->whereDate('end_date', '<=', '2021-02-02');
});

如果真值检查通过,则调用第一个闭包,如果真值检查失败,则执行第二个闭包。

您显然需要将 1==1 替换为要运行的实际相等性检查,因为 1==1 将始终为真...

相关问题