Laravel 数据库:合并多个 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();
是否有比这更好的实现方式吗?
答案
在 Laravel 5.3 你可以传递一个 wheres 数组:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
自2014年6月起,你可以将数组传递给 where
,
只要你想要所有 wheres
使用 and
运算符,你就可以用这种方式对它们进行分组:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
// 如果你需要 or where 语句,同理:
$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 ...)
其他选项
查询作用域可以帮助你把代码变的更具可读性。
在你的模型中,创建像这样的作用域方法:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeThat($query)
{
return $query->where('that', '=', 1);
}
然后,你就可以在构建查询时调用此方法:
$users = User::active()->that()->get();
推荐文章: