Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 + Doctrine: How to supress SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I've looked into a couple of posts, but couldn't find a working solution.

My question is beyond simple:

I have an entity with say id, url and title. The URL should be unique (in MySQL PDO). I've managed to create both the entity and schema with no problems. Now when I walk some records I call persist() on each, and finaly a flush(). The problem is that when I try to insert duplicate entries for the URL it gives me an exception. How to supress it?

When a duplicate entry is being inserted it should just skip it and insert the rest. No need for events, ON UPDATE statements, triggers and all that fancy stuff.

I've tried catching any exceptions thrown by persist or flush(), but can't really seem to do it correctly.

Any ideas are welcome, thank you!

EDIT: Found my solution in here: Symfony2 Controller won't catch exception

like image 210
Tony Bogdanov Avatar asked Dec 01 '22 06:12

Tony Bogdanov


2 Answers

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

try {
    ...
} catch (\Doctrine\DBAL\DBALException $e) {
    // ... Error on database call
}
like image 188
ihsan Avatar answered Dec 14 '22 23:12

ihsan


Be aware that there is a PDOException thrown in Symfony 2.1 if you are e.g. deleting an entry with parent-relations. But in order to catch it you will use the statement suggested by ihsan

    try {
        $em = $this->getDoctrine()->getEntityManager();
        $em->remove($entity);
        $em->flush();
    } catch(\Doctrine\DBAL\DBALException $e)
    {
        // ...
    }
like image 24
ferdynator Avatar answered Dec 15 '22 00:12

ferdynator