Tony Bogdanov
Tony Bogdanov

Reputation: 7686

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

Upvotes: 4

Views: 16568

Answers (3)

ihsan
ihsan

Reputation: 2289

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

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

Upvotes: 12

ferdynator
ferdynator

Reputation: 6410

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)
    {
        // ...
    }

Upvotes: 6

Pete Mitchell
Pete Mitchell

Reputation: 2879

try {
    $em->flush()
} catch (\PDOException $e) {
    // ... Error on database call
}

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

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

Upvotes: 2

Related Questions