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?

1 Answer 1

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

3
  • 4
    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. Feb 14, 2017 at 20:34
  • 1
    @grantwparks you could place the contains() inside the add method if you always want to make sure that the check happens before adding.
    – TheGremlyn
    Aug 18, 2017 at 17:55
  • 2
    @grantwparks 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.
    – jlh
    Nov 23, 2017 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.