Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查集合-Laravel中是否已存在对象_Php_Laravel - Fatal编程技术网

Php 检查集合-Laravel中是否已存在对象

Php 检查集合-Laravel中是否已存在对象,php,laravel,Php,Laravel,我希望在循环一系列不同的结果时,将对象添加到新集合中 查询: $osRed = Item::where('category', 'Hardware') ->where(function ($query) { $query->where('operating_system', 'xxx') ->orWhere('operating_system', 'xxx') ->or

我希望在循环一系列不同的结果时,将对象添加到新集合中

查询:

$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);
            }
        }
}
然后,我转到另一组结果,并将这些结果中的相关服务添加到集合中

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
您可以在定义了键和值的情况下使用:

if (!$servicesImpacted->contains('name', $service->name))
在这种情况下,您也可以使用和收集方法,例如:

if ($servicesImpacted->where('name', $service->name)->count() === 0)
您可以使用Laravel中的contains()方法 检查某个值的特定键是否存在。 如果集合中特定键的值可用,则返回true

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

你能提供你定义的模型和关系吗?看起来,您可以这样编写:Item::where(…)->with('services');因此,
$servicesImpacted
是对象的集合。对吗?谢谢@Alexey仍然在使用'count()方法时遇到字符串错误。但是,您帮助我用contains方法解决了这个问题,它现在正在工作:)为什么这里没有使用相同形式的参数?我很困惑。