我正在寻找将对象添加到新集合中,因为我循环了一系列不同的结果。
查询:
$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();
然后,循环遍历这些结果并将相关对象添加到新集合中。
foreach ($osRed as $os) {
foreach ($os->services as $service) {
if (!($servicesImpacted->contains($service))) {
$servicesImpacted->push($service);
}
}
}
然后,我继续进行另一组结果,并将这些结果中的相关服务添加到集合中。
但是,它并没有意识到对象已经在集合中,并且最终会出现大量(似乎是重复的)重复项。
理想情况下,我想匹配$ service对象的name属性,但contains方法似乎不支持。
toString() must not throw an exception
你可以使用contains()
定义键和值:
if (!$servicesImpacted->contains('name', $service->name))
或者你可以在这种情况下使用where()
和count()
收集方法,例如:
if ($servicesImpacted->where('name', $service->name)->count() === 0)
您可以使用Laravel中的contains()方法检查某些特定的值是否存在。如果特定键的集合中的值可用,则返回true。
if($collection->contains('product_id',1234))
{
echo "product id 1234 available in collection";
}