php - 在 WHERE 中应用 OR 子句或在 Eloquent laravel 中应用 HAVING

标签 php laravel eloquent

我正在开发一个用于构建 REST api 的 laravel 项目。我正在使用 Eloquent 从数据库中获取数据。我在 WHERE、HAVING 等应用 OR 条件时遇到问题。如果只有一个 where 和一个 orWhere 条件,它没有问题,但在这里我采用多个 where 子句。就像我们编写核心 mysql 查询一样,我们可以这样写

SELECT * FROM table_name WHERE uid = 1 
AND (id = 1 AND name = test1) OR (id = 2 AND name = test2);

但是当我们使用 eloquent 时,如果我们在模型中使用 orWhere,为此我们需要做类似的事情

Model::select('*')->where('uid', '1')
->where('id', '1')
->where('name', 'test1')
->orWhere('uid', '1')
->where('id', '1')
->where('name', 'test1')
->get();

有时,当我尝试制作任何可以根据表的参数数量搜索数据的搜索 API 时,我需要多次编写相同的代码。

最佳答案

使用 where()orWhere() 闭包用于参数分组

Model::select('*')->where('uid', '1')->where(function($q){
       $q->where('id', '1')->where('name', 'test1')
    })->orWhere(function($q){
          $q->where('id', '1')->where('name', 'test1')
     })->get();

来自文档

Passing a Closure into the orWhere method instructs the query builder to begin a constraint group. The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.

关于php - 在 WHERE 中应用 OR 子句或在 Eloquent laravel 中应用 HAVING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49249223/

相关文章:

php - 如何在 PHP 中构建分词器?

php - MYSQL如何控制每条记录的最大行数?

php - 目标类 Controller 不存在 - Laravel 8

php - 如何减少子查询的执行时间...?

php - Laravel:如何在一个查询中编写两个查询并从数据库获取结果?

php - Eloquent 使用索引 (IndexRaw) 无法与 join 一起正常工作并且有

php - mysql_fetch_array 不会呈现 SQL 查询的期望值

php - 自动计算mysql表中的数据

php - 使用 Laravel 和 Eloquent 根据兴趣查找建议

php - 方法或位置不存在。拉维尔 5.3