Doctrine2 inheritance - 1452 : Integrity constraint violation

1.3k Views Asked by At

I deployed my projet on a new server and the error "SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" shows up when i try to INSERT a class with inheritance :

/**
 * @ORM\Table(name="prosante")
 * @ORM\Entity
 */

class ProSante extends Base
{

    /**
     * @ORM\Column(type="string")
     */
    protected $firstName;
}


/**
 * @ORM\Table(name="base")
 * @ORM\Entity(repositoryClass="Test\MyBundle\Entity\BaseRepository")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"base" = "Base",
 *                        "prosante" = "ProSante",
 *                        "pharmacie" = "Pharmacie"})
 */

abstract class Base
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
}

Log :

[2012-06-11 15:42:46] doctrine.DEBUG: INSERT INTO base (name) VALUES (?) ({"1":"Blabla"}) [] []
[2012-06-11 15:42:46] doctrine.DEBUG: INSERT INTO prosante (id, firstname) VALUES (?, ?) ({"1":"0","2":"PATRICK"}) [] []

I don't know what to do since the error doesn't show up when i do the same INSERT on localhost.

EDIT I check "SELECT LAST_INSERT_ID();" after manualy insert a new "Base" into my database, its doesn't return 0, i don't understand.

SOLUTION It was a driver problem, i change it and it works.

2

There are 2 best solutions below

3
On

It appears doctrine is interpreting "Base" as its own table. I think what you want to achieve here is to have your Base class as a mapped super class.

To do this simply annotate it as:

@MappedSuperclass

And then you can safely extend it into your other Entities..

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/inheritance-mapping.html#mapped-superclasses

0
On

I experienced quite a similar problem and spent a lot of time searching for its cause, so I allow myself to share my solution here as this is the closest question I found on SO. Hope this may help some people :)

In my case

Doctrine was throwing the same foreign key constraint violation exception, although the auto-generated key in the first query (for base class) was successfully passed on to the second query (for subclass). Second query was still failing with this constraint violation and transaction was rolled back.

Digging into logs (I'm using MariaDB on CentOS), I found this error:

[ERROR] Transaction not registered for MariaDB 2PC, but transaction is active

My solution

It turned out my MariaDB service was improperly installed or updated (I don't know exactly, someone else did it).

Running mysql_upgrade solved my issue.