[英]Apply OR clause in WHERE or HAVING in eloquent laravel
I am working on a laravel project for building REST api. 我正在一个用于构建REST api的laravel项目中。 I am using eloquent to fatch data from database.
我正在雄辩地从数据库获取数据。 I am facing issues in applying the OR condition in WHERE, HAVING etc. If there is only one where and one orWhere condition, it has no issues but here I am taking multiple where clause.
我在WHERE,HAVING等中应用OR条件时遇到问题。如果只有一个where和一个orWhere条件,则没有问题,但是在这里我采用了多个where子句。 Like if we write core mysql query we can write like
就像我们编写核心mysql查询一样
SELECT * FROM table_name WHERE uid = 1
AND (id = 1 AND name = test1) OR (id = 2 AND name = test2);
But when we work with eloquent and if we use orWhere in models, for that we need to do something like 但是当我们雄辩地工作并且如果在模型中使用orWhere时,为此我们需要做一些类似的事情
Model::select('*')->where('uid', '1')
->where('id', '1')
->where('name', 'test1')
->orWhere('uid', '1')
->where('id', '1')
->where('name', 'test1')
->get();
Sometimes when I try to make any search API that can search data baseed on numbers of parameter of the table, I need to write same code multiple time. 有时,当我尝试制作任何可以基于表参数数量搜索数据的搜索API时,我需要多次编写相同的代码。
Use where() or orWhere()
closure for parameter grouping
使用where()或
orWhere()
闭包进行parameter grouping
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();
From Docs 从文档
Passing a
Closure
into theorWhere
method instructs the query builder to begin a constraint group.将
Closure
传递给orWhere
方法将指示查询构建器开始约束组。 The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.闭包将收到一个查询构建器实例,您可以使用它来设置应包含在括号组中的约束。
The equivalent in eloquent
of parenthesis would be using a closure as the parameter of where
or orWhere
eloquent
的等效语是使用闭包作为where
或orWhere
的参数
(a or b) and (c or d)
would be: (a or b) and (c or d)
为:
->where(function($q){
$q->where(a)->orWhere(b);
})->where(function($q){
$q->where(c)->orWhere(d);
});
and 和
(a and b) or (c and d)
would be: (a and b) or (c and d)
将是:
->where(function($q){
$q->where(a)->where(b);
})->orWhere(function($q){
$q->where(c)->where(d);
});
but 但
a or b and c or d
would be: a or b and c or d
为:
->where(a)->orWhere(b)->where(c)->orWhere(d)
which is something completely different. 这是完全不同的东西。
This code will be helpfull for you 此代码将对您有所帮助
Model::where([['uid', '1'],['id', '1'],['name', 'test1']])
->orWhere([['uid', '1'],['id', '1'],['name', 'test1']])
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.