php - laravel 集合复杂和/或表达式

标签 php mysql laravel collections

尝试使用 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/

相关文章:

php - php将数据插入mysql数据库,显示错误

php - Twitter App 没有将 localhost 和 127.0.0.1 作为 CallbackUrl

MySQL 选择不同于表?

php - 如何在 php 中使用 mysql IN() 函数?

php - laravel 5.1同时注册、更新用户信息和发送数据到两个表

javascript - 在javascript数组中动态添加数据

php - PHP 翻译

mysql - 如何使用 BETWEEN DATE 条件在交叉/左连接 MYSQL 中显示空值或零值

mysql - 如果要更新的数据字段有多项选择,那么如何编写更新查询更好?

php - 显示 WooCommerce 可变产品选项