14

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?

Pmpr
  • 14,501
  • 21
  • 73
  • 91
spiil
  • 598
  • 3
  • 7
  • 19

1 Answers1

31

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

Airam
  • 2,000
  • 2
  • 16
  • 32
  • 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. – grantwparks Feb 14 '17 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 '17 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 '17 at 09:15