Doctrine2: check if exists value in Doctrine Collection

spiil picture spiil · Jan 31, 2015 · Viewed 27.9k times · Source

How can I check that given value exists in Doctrine Collection (ManyToMany relation) field?

For example I try to:

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

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

    $entity->addMyCollectionValue($someClass);

}

But it is of course not correct. So, how to avoid for duplicate keys?

Answer

Airam picture Airam · Jan 31, 2015

You could do:

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

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

You could look at the available functions of Doctrine ArrayCollection in http://www.doctrine-project.org/api/common/2.1/class-Doctrine.Common.Collections.ArrayCollection.html