提问者:小点点

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


我正在使用Laravel Eleoquent查询生成器,并且我有一个查询where我想要一个关于多个条件的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();

有没有更好的方法做到这一点,还是我应该坚持这个方法?


共2个答案

匿名用户

在Laravel 5.3中(在7.x中仍为真),可以使用更细粒度的数组:

$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])

就我个人而言,我还没有找到多个where调用的用例,但事实是您可以使用它。

自2014年6月起,您可以将数组传递给where

只要您希望所有wheres使用运算符,就可以通过以下方式对它们进行分组:

$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 ...)

匿名用户

查询范围可以帮助您提高代码的可读性。

http://laravel.com/docs/eLoquent#query-scopes

使用以下示例更新此答案:

在模型中,创建scopes方法,如下所示:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

然后,您可以在生成查询时调用以下作用域:

$users = User::active()->that()->get();