Doctrine2: check if exists value in Doctrine Collection
Asked Answered
S

1

15

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?

Severance answered 31/1, 2015 at 14:56 Comment(0)
T
34

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

Teresetereshkova answered 31/1, 2015 at 15:36 Comment(3)
Is there a Doctrine way of checking without executing another query at the beginning to fetch the object we're searching for, when we already have the id of that object? Why can't I ask the collection if it has an entry with that id? I'm not OK with adding another query for that.Rape
@Rape you could place the contains() inside the add method if you always want to make sure that the check happens before adding.Sheepdog
@Rape Yes, you can get an entity reference with $object = $em->getReference('MyBundle:MyClass', $id), which will return a reference if the entity is already in the cache, or a lazy reference if it isn't. Calling $object->getId() won't cause an entity load, which is what I presume contains() uses.Careless

© 2022 - 2024 — McMap. All rights reserved.