Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert ignore on duplicate entries in Doctrine2/Symfony2

How to ignore on duplicate entries using Doctrine2?

Error example:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'symfony' for key 'UNIQ_389B783389B783'
like image 338
seferov Avatar asked Mar 14 '12 09:03

seferov


3 Answers

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.

like image 178
ILikeTacos Avatar answered Nov 20 '22 07:11

ILikeTacos


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();
}
like image 32
Andrey Rudenko Avatar answered Nov 20 '22 09:11

Andrey Rudenko


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.

like image 13
Cerad Avatar answered Nov 20 '22 09:11

Cerad