我正在使用 Laravel Eloquent 查询生成器,并且我有一个查询,我希望在多个条件下使用 WHERE
子句。它有效,但并不优雅。
例子:
$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();
有没有更好的方法来做到这一点,还是我应该坚持这种方法?
最佳答案
在 Laravel 5.3 (从 7.x 开始仍然如此)您可以使用更精细的 wheres 作为数组传递:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
就我个人而言,我还没有通过多个 where
调用找到这个用例,但事实上你可以使用它。
自 2014 年 6 月起,您可以将数组传递给 where
只要你想让所有的wheres
都使用and
操作符,你可以这样分组:
$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();
上面会产生这样的查询:
SELECT * FROM users
WHERE (field = value AND another_field = another_value AND ...)
OR (yet_another_field = yet_another_value AND ...)
关于php - 如何使用 Laravel Eloquent 创建多个 Where 子句查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325312/