laravel - 使用 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');
}
解决方案
您可能正在寻找条件从句
$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
这始终是正确的...
推荐阅读
- php - 获取当前时间,将其设置为不更新的变量
- java - 如何使用放心验证带有特殊字符的响应正文?
- jquery - Laravel 中基于 Ajax 的自动完成功能太慢
- python - 如何为我的 Dash 应用程序正确添加样式?
- .net - 单元测试 web api
- python - 将 auth_views.login 从 django 1 转换为 2
- arrays - 试图删除数组中的 _id。它似乎不起作用
- node.js - 如何使用 nodejs 进行解析设置?
- azure - AzurePerformanceDiagnostics 扩展与 Azure Log Analytics
- sql - 将 mssql openjson 数组类型值结果转换为表?