gpt4 book ai didi

mysql - 带有空白变量的 Where 子句 Laravel

转载 作者:行者123 更新时间:2023-11-29 05:12:02 26 4
gpt4 key购买 nike

我使用 GET 来收集变量:

$subid = $_GET['subid'];

在我的数据库查询中,我有以下内容:

->where('subID', '=', $subid)

现在如果变量 $subid 为空,则结果不返回任何信息。如何在查询中指定如果变量 $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));
})

关于mysql - 带有空白变量的 Where 子句 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com