Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2: check if exists value in Doctrine Collection

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?

like image 842
spiilmusic Avatar asked Jan 31 '15 14:01

spiilmusic


1 Answers

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

like image 104
Airam Avatar answered Oct 12 '22 12:10

Airam