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

2024-06-21

我正在使用 Laravel Eloquent 查询构建器,并且我有一个查询,我想要一个WHERE多个条件的子句。它可以工作,但并不优雅。

Example:

$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();

有没有更好的方法来做到这一点,或者我应该坚持这种方法?


In 拉拉维尔 5.3 https://laravel.com/docs/5.3/queries#where-clauses(并且截至目前仍然如此7.x https://laravel.com/docs/7.x/queries#where-clauses)您可以使用更细粒度的 wheres 作为数组传递:

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

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

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

只要你想要所有的wheres use 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', ...];

Then:

$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 ...)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Laravel Eloquent 创建多个Where子句查询? 的相关文章

随机推荐