如何使用 Laravel Eloquent 创建多个 Where 子句查询? [英] How to Create Multiple Where Clause Query Using Laravel Eloquent?
问题描述
我正在使用 Laravel Eloquent 查询构建器,并且我有一个查询,我希望在多个条件下使用 WHERE
子句.它有效,但并不优雅.
I'm using the Laravel Eloquent query builder and I have a query where I want a WHERE
clause on multiple conditions. It works, but it's not elegant.
示例:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();
有没有更好的方法可以做到这一点,还是我应该坚持使用这种方法?
Is there a better way to do this, or should I stick with this method?
推荐答案
在 Laravel 5.3(从 7.x 开始仍然如此) 您可以使用更细粒度的 wheres 作为数组传递:
In Laravel 5.3 (and still true as of 7.x) you can use more granular wheres passed as an array:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
就我个人而言,我还没有通过多次 where
调用找到这个用例,但事实是你可以使用它.
Personally I haven't found use-case for this over just multiple where
calls, but fact is you can use it.
自 2014 年 6 月起,您可以将数组传递给 where
只要你想让所有的 wheres
使用 and
操作符,你就可以这样分组:
As long as you want all the wheres
use and
operator, you can group them this way:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
那么:
$results = User::where($matchThese)->get();
// with another group
$results = User::where($matchThese)
->orWhere($orThose)
->get();
以上将导致这样的查询:
The above will result in such query:
SELECT * FROM users
WHERE (field = value AND another_field = another_value AND ...)
OR (yet_another_field = yet_another_value AND ...)
这篇关于如何使用 Laravel Eloquent 创建多个 Where 子句查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!