doctrine2 constraint violation

2019-08-05 10:53发布

I have the following entity with this rekation:

/**
* Acme\DemoBundle\Entity\Book
*
* @ORM\Table(name="book")
* @ORM\Entity(repositoryClass="Acme\DemoBundle\Repository\BookRepository")  
* @ORM\HasLifecycleCallbacks  
* @UniqueEntity(fields="publickey", groups={"publickey"})
*/
class P1guestlistentry {
/**
 * @var P1guestlistentrystatistic
 *
 * @ORM\OneToOne(targetEntity="P1guestlistentrystatistic", orphanRemoval=true, cascade={"all"}, fetch="EAGER")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="fkstatistic", referencedColumnName="pkId", nullable=false)
 * })
 */
private $fkstatistic;

When I try to remove an object like here:

$this->getEntityManager()->getConnection()->beginTransaction();
try{

     $book = $this->getEntityManager()->getRepository('AchmeDemoBundle:Book')->find(3928);
     $this->getEntityManager()->remove($book);
     $this->getEntityManager()->flush();
     $this->getEntityManager()->getConnection()->commit();         
   }catch(Exception $e){
     $this->getEntityManager()->getConnection()->rollBack();
     echo $e->getMessage();
   }
exit;

I can do whatever I want, I get the following error:

An exception occurred while executing 'DELETE FROM book WHERE pkId = ?' with params {"1":3928}: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (p1.book, CONSTRAINT FK_F51A442F78734022 FOREIGN KEY (fkstatistic) REFERENCES bookstatistic (pkId))

Has anbybody an idea what I'm doing wrong? I tried a lot of methods but nothing helps.

1条回答
The star\"
2楼-- · 2019-08-05 11:36

In case someone runs into a similar issue, here is the solution:

/**
 * @var statistic
 *
 * @ORM\OneToOne(targetEntity="statistic", cascade="ALL")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="fkStatistic", referencedColumnName="pkId", onDelete="SET NULL")
 * })
 */

The onDelete option will remove the relation first and then doctrine will do the cascade operation.

查看更多
登录 后发表回答