Symfony 如何搜索对象数组?
我有一个对象数组Symfony 如何搜索对象数组?,symfony,doctrine-orm,Symfony,Doctrine Orm,我有一个对象数组 $states = $this->getDoctrine()->getRepository(LocationState::class)->findAll(); 如何检查$states是否包含包含数据的对象 LocationState {#102960 ▼ -id: 1 -ident: "02" -name: "NAME" -country: LocationCountry {#102992 ▶} } 这不是ArrayCollection,而
$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();
如何检查$states
是否包含包含数据的对象
LocationState {#102960 ▼
-id: 1
-ident: "02"
-name: "NAME"
-country: LocationCountry {#102992 ▶}
}
这不是ArrayCollection,而是对象数组。如果希望查询检索对象:
$this->getDoctrine()->getRepository(LocationState::class)
->findBy(['name' => 'NAME', 'ident' => '02']);
如果只想知道集合中是否有指定的对象,则必须使用一些代码
$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();
$found = false;
foreach($state in $states) {
if($state->getName() == 'NAME' && $state->getIdent() == '02' ) {
$found = true;
}
}
对于对象数组:
$found = !empty(array_filter($objects, function ( $obj ) {
return $obj->name == 'NAME' && $obj->id == 1;
}));
对于ArrayCollection:
$found = $objects->exists(function ( $obj ) {
return $obj->name == 'NAME' && $obj->id == 1;
});
您所说的
包含有数据的对象是什么意思?
?是的,举个例子。对象中包含特定数据。我想检查数组是否包含ident==02且name==name的对象。我可以写forceh,它将循环数组,但我认为这不是一个好主意,因为它的性能可能重复是第二个问题。我必须在集合中找到指定的对象。我做了类似的函数。我认为这是某种php或doctrine帮助函数来实现的。谢谢。