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

标签 php laravel eloquent laravel-query-builder

我正在使用 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/

相关文章:

mysql - 根据特定列数对表进行排序

mysql - 如何仅将没有加入记录的模型添加到集合中 - Eloquent

javascript - php脚本执行超时

Laravel 4 模型单元测试与 Codeception - 未找到类 'Eloquent'

mysql - 将laravel与docker上的mysql容器连接

laravel - Eloquent Where 子句中的类似通配符的语法?

php - Laravel:根据 Eloquent 关系获取用户

php - 需要在我的 globalStyles.css 文件中使用 php block

php - mysql_fetch_array() : supplied argument is not a valid MySQL result resource in C:\wamp\www\mahesh\login\orderhistory. php 第 48 行

php - 比较运算符行为不当