Doctrine ORM错误:外键约束失败

时间:2013-12-23 07:30:04

标签: orm doctrine

每当我尝试删除/删除实体“候选人”时,我都会收到此错误:

An exception occurred while executing 'DELETE FROM candidate WHERE id = ?' with params {"1":3}: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`ima`.`result`, CONSTRAINT `result_ibfk_2` FOREIGN KEY (`test_id`) REFERENCES `Test` (`id`))

以下是所涉及的Doctrine ORM实体的关系:

实体:候选人

/**
 * @OneToMany(targetEntity="Test", mappedBy="candidate",
 * cascade={"persist"})
 * 
 * @var ArrayCollection
 */
private $tests;

实体:测试

/**
 * @ManyToOne(targetEntity="Candidate", inversedBy="tests")
 * @JoinColumn(name="candidate_id", referencedColumnName="id", onDelete="cascade")
 */
private $candidate;

 /**
 * @OneToMany(targetEntity="Answer", mappedBy="test", cascade={"persist", "remove"})
 * @var ArrayCollection
 */
private $answers;

/**
 * @OneToMany(targetEntity="Result", mappedBy="test", cascade={"persist"})
 * @var ArrayCollection
 */
private $results;

实体:回答

/**
 * @ManyToOne(targetEntity="Test", inversedBy="answers")
 * @JoinColumn(name="test_id", referencedColumnName="id")
 */
private $test;

实体:结果

/**
 * @ManyToOne(targetEntity="Test", inversedBy="results")
 */
protected $test;

我做错了什么?请帮忙。感谢。

2 个答案:

答案 0 :(得分:1)

除非您删除该候选人的相应测试,否则您无法删除候选人。它是一个数据库问题,好像你删除了卡迪亚斯他将采取的测试会发生什么?在那个外键上应该是set null on delete

我也看到你在候选类的代码中使用了cascade={"persist"}。因此,从reference of doctrine开始,您需要首先删除该候选项的那些测试,然后删除候选项本身(),您也可以使用其他级联方法)。请查看该段,因为它解释了您的问题。感谢

答案 1 :(得分:0)

我终于用Gunner Aziz的小费解决了这个问题。

// Delete results.
$test = $candidate->getLatestTest();
$results = $test->getResults();
foreach ($results as $result) {
        $em->remove($result);
        $em->flush();
}

// Delete test.
$em->remove($test);
$em->flush();

// Delete candidate
$em->remove($candidate);
$em->flush();

实体:当我删除实体时会自动删除'回答':'测试',因为它是从那里级联的。