„insert ignore on duplicate entries“ in Doctrine / Symfony

As it’s not possible to do insert or update ignore in doctrine, those who still want to ignore entities when they are already in the database might find this snippet useful:

$doctrine = $this->getContainer()->get('doctrine');
  foreach ($entities as $entity) {
    try {
      $em = $doctrine->getManager();
    } catch (UniqueConstraintViolationException $e) {


Calling $doctrine->resetManager(); is necessary as the entity manager will be closed otherwise and you will not be able to use it anymore.

Please be aware that the disadvantage of that solution is a huge performance decrease as we are flushing the entity manager every round.

Februar 16th, 2018