首页 > 解决方案 > Doctrine 合并实体与单向 OneToMany 不清除数据库条目

问题描述

首先,我使用 Doctrine v2.6.2 和 Symfony v4.1.7。

我有一个实体Product(除其他外)与另一个实体具有单向的一对多关系AlternativeDuration。按照 Doctrine 的文档,我的产品类中的映射如下所示:

/**
 * @ORM\ManyToMany(
 *     targetEntity="AlternativeDuration",
 *     cascade={"persist", "merge", "remove"},
 *     orphanRemoval=true
 *   )
 * @ORM\JoinTable(name="ProductAlternativeDurations",
 *   joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)},
 *   inverseJoinColumns={@ORM\JoinColumn(name="alternative_duration_id", referencedColumnName="id", unique=true, onDelete="CASCADE", nullable=false)}
 * )
 */
 protected $alternativeDurations;

我的应用程序最近开始使用 React,这意味着我现在提交了我的产品的 JSON 表示(以及一系列替代持续时间),我需要将其反序列化到Product后端的实体中。我为此使用具有默认配置的 JMS 序列化程序。

现在我在编辑现有产品时遇到了问题,该产品已经有一个我删除的替代持续时间。提交的 JSON 如下所示:

{
    "id": 1,                      # the ID of the existing product here
    "alternativeDurations": []    # empty array because the entry is removed
}

在后端,我成功反序列化了 JSON 字符串:

$serializedProduct = $this->serializer->deserialize($jsonString, Product::class, 'json');

我在这里验证了$serializedProduct没有替代的持续时间。然后我跟着合并+刷新。我希望合并能够获取现有产品并用$serializedProduct.

$em->merge($serializedProduct);    # $em being the EntityManager.
$em->flush();

现在我希望该AlternativeDuration条目以及ProductAlternativeDurations连接表条目被删除。ProductAlternativeDurations但是,结果是删除了in 的条目,但AlternativeDuration仍然存在。

我现在很茫然,任何人都可以指点为什么该AlternativeDuration条目没有被删除?

编辑 19-11-2018:

看来这是 Doctrine 中的一个已知错误:#2542

merge将在 Doctrine3 中删除,所以我可能需要重新考虑这种方法。

标签: phpdoctrine-ormsymfony4

解决方案


推荐阅读