Laravel 集合多个 where 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44307902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel collection multiple where conditions
提问by Stefano Maglione
Following this post How to create multiple where clause query using Laravel Eloquent?
遵循这篇文章如何使用 Laravel Eloquent 创建多个 where 子句查询?
I am trying to insert multiple 'and' conditions:
我正在尝试插入多个“和”条件:
$matchThese = ['destination.country' => 'china', 'doc.description' => 'business'];
return $collection->where($matchThese);
but I receive this error:
但我收到此错误:
Too few arguments to function Illuminate\Support\Collection::where(), 1 passed . . . but two expected
回答by Sandeesh
Collection wheremethod doesn't accept an array of conditions like eloquent does. But you can chain multiple where conditions.
Collectionwhere方法不接受像 eloquent 那样的条件数组。但是您可以链接多个 where 条件。
return $collection->where('destination.country', 'china')
->where('doc.description', 'business');
Example
例子
$data = [
['name' => 'john', 'email' => '[email protected]'],
['name' => 'john', 'email' => '[email protected]'],
['name' => 'kary', 'email' => '[email protected]'],
];
$collection = collect($data);
$result = $collection->where('name', 'john');
// [{"name":"john","email":"[email protected]"},{"name":"john","email":"[email protected]"}]
$result = $collection->where('name', 'john')->where('email', '[email protected]');
// [{"name":"john","email":"[email protected]"}]
回答by Guillaume Boutin
Chaining multiple wheres will surely work, but you will do a loop for each one of them. Use filterinstead. That will loop through and check for all your conditions only once.
链接多个wheres 肯定会起作用,但是您将为每个 s 做一个循环。改用过滤器。这将循环并仅检查一次您的所有条件。
$matchThese = ['destination.country' => 'china', 'doc.description' => 'business'];
return $collection->filter(function ($item) use ($matchThese) {
foreach ($matchThese as $key => $value) {
if ($item[$key] !== $value) {
return false;
}
}
return true;
});
回答by utdev
Since whereexpects or needs more then one parameter, it does not work.
由于where期望或需要多个参数,因此它不起作用。
That is what your error says:
这就是你的错误所说的:
Too few arguments to function where(), 1 passed . . . but two expected
函数 where() 的参数太少,1 通过。. . 但两个预期
You could probably do something like this:
你可能会做这样的事情:
return $collection->where($matchThese[0], $matchThese[1]);
Or this
或这个
return $collection->where($matchThese[0], OPERATOR, $matchThese[1]); // OPERATOR could be `=` or `<>`
So to have multiple where conditions one can do something like this:
因此,要拥有多个 where 条件,可以执行以下操作:
return $collection->where($matchThese[0], $matchThese[1])
->where($foo, $bar);
you can basically just chain them.
您基本上可以将它们链接起来。

