2016-02-05 66 views
0

我有兩個相關對象:級聯工作,其混亂

用戶

/** 
* @ORM\OneToOne(targetEntity="File", mappedBy="userProfileImage") 
*/ 
protected $profileImage; 

文件在我的數據庫

/** 
* @ORM\OneToOne(targetEntity="User", inversedBy="profileImage") 
* @ORM\JoinColumn(name="userProfileImage", referencedColumnName="id", onDelete="SET NULL") 
*/ 
protected $userProfileImage; 

和兩個相關記錄。我想刪除舊的File對象並將其替換爲新的File。問題是我無法刪除文件的對象,因爲我有以下錯誤:

$this->getDoctrine()-getManager()->remove($user->getProfileImage()); 
$this->getDoctrine()-getManager()->flush(); 

我嘗試添加cascade={"all"}cascade={"persist", "remove"}$profileImage

A new entity was found through the relationship 'MyBundle\Entity\User#profileImage' that was not configured to cascade persist operations for entity: MyBundle\Entity\[email protected] To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'MyBundle\Entity\File#__toString()' to get a clue.

在我看來移除應該工作打完電話後註釋但沒有成功。我需要有人來解釋我做錯了什麼,我該怎麼做。

回答

0

我找到了解決辦法: 要刪除相關對象,我不應該刪除直接:

$this->getDoctrine()-getManager()->remove($file); 

而是通過用戶:

$userFile = $user->getProfileImage(); 
$this->getDoctrine()-getManager()->remove($userFile); 
$this->getDoctrine()-getManager()->remove($file); 

此外,有必要之前和上面的代碼之後調用flush()

$this->getDoctrine()-getManager()->flush(); 

$userFile = $user->getProfileImage(); 
$this->getDoctrine()-getManager()->remove($userFile); 
$this->getDoctrine()-getManager()->remove($file); 

$this->getDoctrine()-getManager()->flush(); 

我不知道爲什麼,但它工作正常,我也許這將是有用的人了。

它並沒有改變這個事實,這是一個非常難看的解決方案,所以如果有人知道如何改進這段代碼,請告訴我!我會很感激。

0

我不知道如果是這樣的解決方案,但我THIK應該相當明確地告訴級聯刪除上

/** 
* @ORM\OneToOne(targetEntity="User", inversedBy="profileImage", cascade={"persist", "remove") 
* @ORM\JoinColumn(name="userProfileImage", referencedColumnName="id", onDelete="CASCADE") 
*/ 
protected $userProfileImage;