Doctrine2:检查Doctrine Collection中是否存在值

时间:2015-01-31 14:56:52

标签: symfony doctrine-orm arraycollection

如何检查 Doctrine Collection (ManyToMany关系)字段中是否存在给定值?

例如我尝试:

$someClass = $this->
             getDoctrine()->
             getRepository('MyBundle:MyClass')->
             find($id);

if (!$entity->getMyCollectionValues()->get($someClass->getId())) {

    $entity->addMyCollectionValue($someClass);

}

但它当然不正确。那么,如何避免重复键?

1 个答案:

答案 0 :(得分:27)

你可以这样做:

$object = $this->getDoctrine()->getRepository('MyBundle:MyClass')->find($id);

if ( !$entity->getMyCollectionValues()->contains($object) ) {
    $entity->addMyCollectionValue($object);
}

您可以在http://www.doctrine-project.org/api/common/2.1/class-Doctrine.Common.Collections.ArrayCollection.html

中查看Doctrine ArrayCollection的可用功能