[英]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
是一个抽象类,其中包含一些子类的公共变量。 Subclass1
和Subclass2
是MappedSuperclass
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::$mappedSuperclasses
的targetEntity
更改为Subclass1
或Subclass2
,它将起作用。 我的设置无法实现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;
}
问题解决后,我回答了一年,但我遇到了同样的问题。 当我尝试清空countArrayCollection时发生错误。
因此解决方案是检查$ this-> entity是否为array,然后返回其长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.