如何使用 Laravel 查询构建器在 WHERE 条件周围添加括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22694866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add brackets around WHERE conditions with Laravel query builder
提问by mtmacdonald
I'm using the Laravel query builder to dynamically filter data based on a user's filter selections:
我正在使用 Laravel 查询构建器根据用户的过滤器选择动态过滤数据:
$query = DB::table('readings');
foreach ($selections as $selection) {
$query->orWhere('id', $selection);
}
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');
When I examine the SQL, I get something like this:
当我检查 SQL 时,我得到如下信息:
select count(*) as `count` from `readings` where `id` = 1 or id` = 2 and `date` between "2013-09-01" and "2013-09-31" group by `id`;
But what I need is something like this (with brackets around the or statements):
但我需要的是这样的(在 or 语句周围加上括号):
select count(*) as `count` from `readings` where (`id` = 1 or id` = 2) and `date` between "2013-09-01" and "2013-09-31" group by `id`;
How do I add brackets around WHERE conditions with Laravel query builder?
如何使用 Laravel 查询构建器在 WHERE 条件周围添加括号?
采纳答案by mtmacdonald
Solved this myself by using a closure, as described in Parameter Groupingin the query builder documentation.
通过使用闭包自己解决了这个问题,如查询构建器文档中的参数分组中所述。
$query = DB::table('readings');
$this->builder->orWhere(function($query) use ($selections)
{
foreach ($selections as $selection) {
$query->orWhere('id', $selection);
}
});
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');
回答by Gonzalo Tito
Very useful, I use this:
非常有用,我用这个:
->where(function ($query) use ($texto){
$query->where('UPPER(V_CODIGO)', 'LIKE', '%'.Str::upper($texto).'%')
->orWhere('UPPER(V_NOMBRE)', 'LIKE', '%'.Str::upper($texto).'%');
});
回答by Furkan Mustafa
I couldn't find this in documentation, whereNested
was what I was looking for. Hope it helps anybody.
我在文档中找不到这个,whereNested
这就是我要找的。希望它可以帮助任何人。
$q->whereNested(function($q) use ($nameSearch) {
$q->where('name', 'LIKE', "%{$nameSearch}%");
$q->orWhere('surname', 'LIKE', "%{$nameSearch}%");
});
Note: This is on Laravel 4.2
注意:这是在 Laravel 4.2 上
回答by Wesley Murch
You can use WHERE IN
here for the same effect:
您可以WHERE IN
在此处使用以获得相同的效果:
$query = DB::table('readings');
$query->whereIn('id', $selection)
$query->whereBetween('date', array($from, $to));
$query->groupBy('id');