Symfony 2 + Doctrine: How to Suppress SQLSTATE [23000]: Violation of Integrity Constraints: 1062 Duplicate Records

I looked through a few posts but did not find a working solution.

My question is simple:

I have an entity with the words id , url and title . The URL must be unique (in MySQL PDO). I managed to create both an entity and a schema without problems. Now that I am going through a few entries, I call persist() for each, and finaly a flush() . The problem is that when I try to insert duplicate entries for the url, this gives me an exception. How to suppress it?

When a duplicate entry is inserted, it should just skip it and insert the rest. There is no need for events, UPDATE operations, triggers, and all these bizarre things.

I tried to catch any exceptions thrown by persist or flush() , but it may not seem like this is correct.

Any ideas are welcome, thanks!

EDIT: found my solution here: Symfony2 controller will not catch exception

+4
source share
3 answers
 try { $em->flush() } catch (\PDOException $e) { // ... Error on database call } 

A better approach would be to specify a check constraint to avoid having to deal with this exception. In yaml (taken from symfony docs )

 Acme\SomeBundle\Entity\Item: constraints: - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: url 
+2
source

In Symfony 2.1+, catch it using \Doctrine\DBAL\DBALException instead of \PDOException .

 try { ... } catch (\Doctrine\DBAL\DBALException $e) { // ... Error on database call } 
+12
source

Remember that Symfony 2.1 has a PDOException if you, for example. Deleting a record with a parent relationship. But to catch it, you will use the statement proposed by ihsan

  try { $em = $this->getDoctrine()->getEntityManager(); $em->remove($entity); $em->flush(); } catch(\Doctrine\DBAL\DBALException $e) { // ... } 
+6
source

Source: https://habr.com/ru/post/1395514/


All Articles