【问题标题】:Laravel collection multiple where conditionsLaravel 集合多个 where 条件
【发布时间】:2017-11-02 14:58:28
【问题描述】:

关注这个帖子How to create multiple where clause query using Laravel Eloquent?

我正在尝试插入多个“和”条件:

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

    return $collection->where($matchThese);

但我收到此错误:

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

【问题讨论】:

  • where 需要两个参数,您可能可以这样做 return $collection->where($matchThese[0], $matchThese[1]);

标签: php laravel laravel-eloquent


【解决方案1】:

由于where 需要或需要多个参数,所以它不起作用。

这就是你的错误所说的:

函数 where() 的参数太少,通过了 1 个。 . .但有两个预期

你可能会这样做:

return $collection->where($matchThese[0], $matchThese[1]);

或者这个

return $collection->where($matchThese[0], OPERATOR, $matchThese[1]); // OPERATOR could be `=` or `<>`

所以有多个 where 条件可以做这样的事情:

return $collection->where($matchThese[0], $matchThese[1])
                  ->where($foo, $bar);

你基本上可以把它们串起来。

【讨论】:

  • 他正在寻找一个有多个 where 条件的答案,而不是正确的输入格式。
【解决方案2】:

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

return $collection->where('destination.country', 'china')
    ->where('doc.description', 'business');

例子

$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"}]

【讨论】:

  • 从 Laravel 文档中可以看出 Collections 与 Eloquent 的相似程度。谢谢!
  • 这适用于和条件
【解决方案3】:

链接多个wheres 肯定会起作用,但是您将为它们中的每一个执行一个循环。请改用filter。这将循环并仅检查一次您的所有条件。

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

【讨论】:

    【解决方案4】:

    这是我对这个问题的解决方案:

        $matchThese = ['country' => 'china', 'description' => 'business'];
        $data = collect([...]);
        $query = null;
    
        foreach ($matchThese as $col => $value) {
            $query = ($query ?? $data)->where($col, $value);
        }
    

    在循环结束时,$query 将包含结果。

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 2016-06-17
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2017-02-05
      • 2017-11-12
      • 1970-01-01
      相关资源
      最近更新 更多