检查Collection - Laravel中是否已存在Object

ker*_*rin 14 php laravel

我正在寻找将对象添加到新集合中,因为我循环了一系列不同的结果.

查询:

$osRed = Item::where('category', 'Hardware')
        ->where(function ($query) {
            $query->where('operating_system', 'xxx')
                ->orWhere('operating_system', 'xxx')
                ->orWhere('operating_system', 'xxx');
        })
        ->orderBy('operating_system', 'ASC')
        ->get();
Run Code Online (Sandbox Code Playgroud)

然后,循环遍历这些结果并将相关对象添加到新集合中.

foreach ($osRed as $os) {
        foreach ($os->services as $service) {
            if (!($servicesImpacted->contains($service))) {
                $servicesImpacted->push($service);
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

然后,我继续进行另一组结果,并将这些结果中的相关服务添加到集合中.

但是,它并没有意识到对象已经在集合中,并且最终会出现大量(似乎是重复的)重复项.

理想情况下,我想匹配$ service对象的name属性,但contains方法似乎不支持.

toString() must not throw an exception
Run Code Online (Sandbox Code Playgroud)

Ale*_*nin 36

您可以使用contains()键和值定义:

if (!$servicesImpacted->contains('name', $service->name))
Run Code Online (Sandbox Code Playgroud)

或者你可以在这种情况下使用where()count()收集方法,例如:

if ($servicesImpacted->where('name', $service->name)->count() === 0)
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以使用 Laravel 中的 contains() 方法来检查某些特定的值键是否存在。如果特定键的集合中的值可用,则返回 true。

if($collection->contains('product_id',1234))
{
  echo "product id 1234 available in collection";
}
Run Code Online (Sandbox Code Playgroud)