2016-02-05 72 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;