php 检查集合中是否已存在对象 - Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44215902/
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
Check if Object already exists in Collection - Laravel
提问by kerrin
I am looking to add objects to a new collection as I loop through a series of different results.
当我遍历一系列不同的结果时,我希望将对象添加到新集合中。
The query:
查询:
$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();
Then, loop through these results and add related objects to a new collection.
然后,遍历这些结果并将相关对象添加到新集合中。
foreach ($osRed as $os) {
foreach ($os->services as $service) {
if (!($servicesImpacted->contains($service))) {
$servicesImpacted->push($service);
}
}
}
I then go on to another set of results and add the related services from those results to the collection.
然后我继续处理另一组结果并将这些结果中的相关服务添加到集合中。
However, it is not picking up that the object is already in the collection and I end up with a large number of (what appear to be) duplicates.
但是,并没有发现对象已经在集合中,我最终得到了大量(似乎是)重复项。
Ideally, I would like to match up on the name attribute of the $service object, but that doesn't seem to be supported by the contains method.
理想情况下,我想匹配 $service 对象的 name 属性,但 contains 方法似乎不支持。
toString() must not throw an exception
回答by Alexey Mezenin
You can use contains()
with key and value defined:
您可以使用contains()
定义的键和值:
if (!$servicesImpacted->contains('name', $service->name))
Or you could use where()
and count()
collection methods in this case, for example:
或者您可以在这种情况下使用where()
和count()
收集方法,例如:
if ($servicesImpacted->where('name', $service->name)->count() === 0)
回答by Chirag Prajapati
You can use the contains() method in Laravel for Check some specific key of value exists or not. If value available in the collection for the specific key then returns true.
您可以使用 Laravel 中的 contains() 方法来检查某些特定的值键是否存在。如果特定键的集合中的值可用,则返回 true。
if($collection->contains('product_id',1234))
{
echo "product id 1234 available in collection";
}