小编典典

如何使用Laravel Eloquent创建多个Where子句查询?

php

我正在使用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();

有没有更好的方法可以执行此操作,还是应该坚持使用此方法?


阅读 352

收藏
2020-05-26

共1个答案

小编典典

在Laravel 5.3中从6.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 ...)
2020-05-26