繁体   English   中英

Doctrine2级联删除不适用于Abstract Class

[英]Doctrine2 cascade delete doesn't work with Abstract Class

在我用Symfony2构建的Web应用程序中,包含以下实体:

/**
 * @ORM\Entity
 * @ORM\Table
 */
class Entity
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id", type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="MappedSuperclass", mappedBy="entity", cascade={"persist", "remove"})
     */
    private $mappedSuperclasses;
}

/**
 * @ORM\MappedSuperclass
 */
abstract class MappedSuperclass
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id", type="integer")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Entity", inversedBy="mappedSuperclasses")
     * @ORM\JoinColumn(name="entity_id", referencedColumnName="id", nullable=false)
     */
    protected $entity;
}

/**
 * @ORM\Entity
 * @ORM\Table(name="table_1")
 */
class Subclass1 extends MappedSuperclass
{
    /**
     * @ORM\Column(name="unique_member", type="string")
     */
    private $uniqueMember;
}

/**
 * @ORM\Entity
 * @ORM\Table(name="table_2")
 */
class Subclass2 extends MappedSuperclass
{
    /**
     * @ORM\Column(name="unique_member", type="string")
     */
    private $uniqueMember; // This is different from Subclass1
}

我会解释一下。 Entity具有MappedSuperclass的集合。 MappedSuperclass是一个抽象类,其中包含一些子类的公共变量。 Subclass1Subclass2MappedSuperclass Subclass2类。 当从数据库中删除Entity$mappedSuperclasses的项目应一起删除,这就是为什么设置了cascade={"persist", "remove"}

但是,当我尝试删除Entity ,出现以下错误:

ContextErrorException: Notice: Undefined index: entity in C:\\project\\vendor\\doctrine\\orm\\lib\\Doctrine\\ORM\\Persisters\\BasicEntityPersister.php line 1753

如果我将Entity::$mappedSuperclassestargetEntity更改为Subclass1Subclass2 ,它将起作用。 我的设置无法实现ON DELETE CASCADE吗? 我想念什么?

我通过将ON DELETE动作设置为数据库级别来解决此问题:

/**
 * @ORM\Entity
 * @ORM\Table
 */
class Entity
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id", type="integer")
     */
    private $id;
}

/**
 * @ORM\MappedSuperclass
 */
abstract class MappedSuperclass
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(name="id", type="integer")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Entity")
     * @ORM\JoinColumn(name="entity_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     */
    protected $entity;
}

资料来源: [1] [2]

问题解决后,我回答了一年,但我遇到了同样的问题。 当我尝试清空countArrayCollection时发生错误。

因此解决方案是检查$ this-> entity是否为array,然后返回其长度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM