insert ignore on duplicate entries in Doctrine2/Symfony2

In Symfony 3 you can reset manager and continue working with it by calling resetManager() method of Doctrine object after catching UniqueConstraintViolationException exception.

Here is an example:

try {
  $em = $this->getDoctrine()->getManager();
  $entity = Product::create()
    ->setTitle('Some title')
    ->setUrl('http://google.com');
  $em->persist($entity);
  $em->flush();
}
catch (UniqueConstraintViolationException $e) {
  $this->getDoctrine()->resetManager();
}

You can always catch the exception and then ignore it. Just be aware that when the entity manager raises an exception, the entity manager can no longer be used during that request.


That's one of the nuisances of Doctrine, it's not possible to do INSERT/UPDATE Ignore, there are workaround like creating a methods that checks if the row exists, and if it does then just skip it.

You can catch the exception, so that your script doesn't end in an exception. However, the entity manager will be closed and you will not be able to use it anymore. You can still use PDO, though and you can insert a record in the database indicating that your batch failed because X and it needs to be restarted (that's what I usually do).

If none of the options above work for you, ultimately I end up writing raw SQL to do batch processing and I don't use Doctrine at all, it ends up being faster and the ability of doing INSERT/UPDATE Ignore makes it a no brainer.