OneToOne 关系中的级联操作令人困惑

Cascade operation in OneToOne Relationship which is confusing

我有两个相关对象:

用户

/**
 * @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。问题是我无法删除文件对象,因为我有以下错误:

A new entity was found through the relationship 'MyBundle\Entity\User#profileImage' that was not configured to cascade persist operations for entity: MyBundle\Entity\File@000000001604d7ad000000003cc76066. 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.

我认为删除应该在调用后起作用:

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

我尝试将 cascade={"all"}cascade={"persist", "remove"} 添加到 $profileImage 注释,但没有成功。我需要有人来解释我做错了什么以及我应该怎么做。

我不确定这是否是解决方案,但我认为它应该明确告诉级联删除

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

我找到了解决方案: 要删除相关对象,我不应该直接删除它:

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

我不知道为什么,但它对我来说很好用,也许对其他人有用。

这并没有改变一个事实,它是一个非常丑陋的解决方案,所以如果有人知道如何改进这段代码,请告诉我!我将不胜感激。