带有空白变量的 Where 子句 Laravel
Where clause with a blank variable Laravel
我使用 GET 来收集变量 :
$subid = $_GET['subid'];
在我的数据库查询中,我有以下内容:
->where('subID', '=', $subid)
现在如果变量 $subid 为空,结果 return 没有信息。我如何在查询中指定如果变量 $subid 为空或为空,return 所有结果?
您可以使用 orWhere():
->where('subID', '=', $subid)
->orWhere('subID', '=', '');
您可以使用 when
.
->when($subid, function ($query) use ($subid) {
return $query->where('subID', '=', $subid);
})
如果 $subid 为假,where 条件将不会应用于查询。
查看文档 https://laravel.com/docs/5.2/queries#conditional-statements
更新:
可以在 if
调用中使用的任何表达式都可以用作 when
的第一个参数
一个例子:
->when($fromDate && $toDate, function($query) use ($fromDate, $toDate) {
return $query->whereBetween('CompletedDate', array($fromDate, $toDate));
})
我使用 GET 来收集变量 :
$subid = $_GET['subid'];
在我的数据库查询中,我有以下内容:
->where('subID', '=', $subid)
现在如果变量 $subid 为空,结果 return 没有信息。我如何在查询中指定如果变量 $subid 为空或为空,return 所有结果?
您可以使用 orWhere():
->where('subID', '=', $subid)
->orWhere('subID', '=', '');
您可以使用 when
.
->when($subid, function ($query) use ($subid) {
return $query->where('subID', '=', $subid);
})
如果 $subid 为假,where 条件将不会应用于查询。
查看文档 https://laravel.com/docs/5.2/queries#conditional-statements
更新:
可以在 if
调用中使用的任何表达式都可以用作 when
一个例子:
->when($fromDate && $toDate, function($query) use ($fromDate, $toDate) {
return $query->whereBetween('CompletedDate', array($fromDate, $toDate));
})