【问题标题】:Cascading Delete in Class Table Inheritance doesn't delete parent row类表继承中的级联删除不会删除父行
【发布时间】:2020-04-06 09:14:49
【问题描述】:

我有一个名为Notification 的父类,它的子类之一是CommentNotification(类表继承)。

/**
 * This entity represents the notifications that are sent to users when an event happens
 * @ORM\Entity(repositoryClass="AppBundle\Repository\NotificationRepository")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({
 *     "yp" = "YpNotification",
 *     "default" = "Notification",
 *     "comment" = "CommentNotification",
 *     "post" = "PostNotification"})
 * @ORM\Table(name="notification")
 */
class Notification
{
    /**
     * The identifier of this notification
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var int $id
     */
    protected $id;
}

CommentNotification 中,我包含了onDelete = "CASCADE",这样当评论被删除时,附加到它的通知也会被删除。

/**
     * @ORM\Entity
     * @ORM\Table(name="comment_notification")
     * @ORM\Entity(repositoryClass="AppBundle\Entity\Notifications\CommentNotificationRepository")
     */  
class CommentNotification extends Notification
        {

            /**
             *
             * @ORM\ManyToOne(targetEntity="AppBundle\Entity\ContentItem\ContentItemComment")
             * @ORM\JoinColumn(name="comment_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
             */
            private $comment;
    ...
}

根据要求,我也显示 ContentItemComment。这不包含与 CommentNotification 的双向关系。

/**
     * 
     * @ORM\Table(name="content_item_comment")
     * @ORM\Entity(repositoryClass="AppBundle\Entity\ContentItem\ContentItemCommentRepository")
     */
    class ContentItemComment
    {
        /**
         * @ORM\Column(type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;
...
}

但是它成功删除了comment_notification 中的行,但notification 中的行仍然存在,在通知表中留下了我每次都必须手动删除的幽灵记录。

F.e 这个查询每天都会返回一些新结果:

SELECT * FROM `notification` n WHERE n.id not in (select id from comment_notification) and n.type='comment' 

我错过了Notification 中的注释吗?

【问题讨论】:

  • 嗨,你也可以显示ContentItemComment实体吗?是双向的吗?如果尝试在其OneToMany 关系中使用mappedBy="comment", cascade={"remove"}, orphanRemoval=true)
  • @EugeneRuban。添加 orphanRemoval = true 解决了我的问题!我没想到会这样,因为我认为添加它只会删除“评论通知”而不是“通知”。您可以将此添加为答案,以便我接受吗?
  • 很高兴能提供帮助。添加了答案。
  • @EugeneRuban 我接受了。非常感谢:)

标签: symfony annotations doctrine class-table-inheritance


【解决方案1】:

Doctrine site 上有如下注释:

当您不使用 SchemaTool 生成所需的 SQL 时,您应该知道删除类表继承会在所有数据库实现中使用外键属性 ON DELETE CASCADE。自己未能实现这一点将导致数据库中出现死行。

这是可能的原因吗?

【讨论】:

    【解决方案2】:

    正如 cmets 中提到的那样 - 如果它是双向关系 - 您需要将 orphanRemoval=true 选项添加到相关的 OneToMany 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2016-04-06
      • 2014-09-05
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多