首页 > 解决方案 > 使用 if/else 运算符的 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');
}

标签: laravel

解决方案


您可能正在寻找条件从句

$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这始终是正确的...


推荐阅读