gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:30:30 24 4
gpt4 key购买 nike

我正在开发一个用于构建 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/

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