2013-12-23 46 views
2

每當我試圖刪除/刪除實體的「候選」我得到這個錯誤:學說ORM錯誤:外鍵約束失敗

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`)) 

下面是所涉及的學說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; 

我在做什麼錯?請幫忙。謝謝。

回答

1

我終於用槍炮阿齊茲的提示解決了它。

// 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(); 

實體:'答案'將自動刪除時,我試圖刪除實體:'測試',因爲它從那裏級聯。

0

除非刪除該候選人的相應測驗,否則無法刪除候選人。它是一個數據庫問題,就好像你刪除了候選人將會發生的測試他採取了什麼?在外鍵上它應該是set null on delete

我還看到你在代碼中使用了cascade={"persist"}候選類。因此,從reference of doctrine您需要先刪除那些候選人的測試,然後刪除候選人本身(),您也可以使用其他級聯方法)。請參閱該段來解釋您的問題。謝謝