Laravel收集多个条件

Ste*_*one 8 php laravel laravel-eloquent

以下文章如何使用Laravel Eloquent创建多个where子句查询?

我试图插入多个'和'条件:

$matchThese = ['destination.country' => 'china', 'doc.description' => 'business'];

    return $collection->where($matchThese);
Run Code Online (Sandbox Code Playgroud)

但是我收到这个错误:

Too few arguments to function Illuminate\Support\Collection::where(), 1 passed . . . but two expected
Run Code Online (Sandbox Code Playgroud)

San*_*esh 18

Collection where方法不接受像eloquent那样的一系列条件.但你可以链接多个条件.

return $collection->where('destination.country', 'china')
    ->where('doc.description', 'business');
Run Code Online (Sandbox Code Playgroud)

$data = [
    ['name' => 'john', 'email' => 'john@gmail.com'],
    ['name' => 'john', 'email' => 'jim@gmail.com'],
    ['name' => 'kary', 'email' => 'kary@gmail.com'],
];

$collection = collect($data);

$result = $collection->where('name', 'john');
// [{"name":"john","email":"john@gmail.com"},{"name":"john","email":"jim@gmail.com"}]


$result = $collection->where('name', 'john')->where('email', 'john@gmail.com');
// [{"name":"john","email":"john@gmail.com"}]
Run Code Online (Sandbox Code Playgroud)

  • 从 Laravel 文档中看,集合与 Eloquent 的相似程度并不明显。谢谢! (2认同)

小智 10

链接多个wheres 肯定会起作用,但是您将为它们中的每一个执行一个循环。使用过滤器代替。这将循环遍历并仅检查所有条件一次。

$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;
});
Run Code Online (Sandbox Code Playgroud)