尝试使用 and/or where 语句,就好像它们嵌套在括号中一样。 示例:
Select * from myTable
where
(id > 78 or name is not null)
and term_date >= NOW())
尝试让这些复杂的 where 语句在 Laravel 集合中使用,如下所示:
$query = myTableModel::where(['id', '>', 78])
->orWhereNotNull('name')
->where('term_date', '>=', date('Y-m-d'))
但是这种类型的查询会返回这样的where
where
(id > 78 or
name is not null and
term_date >= Now())
或任何其他奇怪的 where 组合,而不是设置嵌套括号。
有没有办法使用 laravel Collections 解决此类问题?
最佳答案
要获取您想要实现的查询,您可以尝试向 where 方法添加回调,并在其中添加 where/orWhere ,如下所示:
$query = myTableModel::where(function($query) {
$query->where('id', '>', 78)
->orWhereNotNull('name');
})->where('term_date', '>=', date('Y-m-d'));
在本地用户模型上运行它会在执行 toSql() 时给出以下结果,这就是我相信您所追求的。
select * from `users` where (`id` > ? or `name` is not null) and `term_date` >= ?
关于php - laravel 集合复杂和/或表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119741/