通过自引用一对多关联从实体中删除子项

Gop*_*yan 3 mapping self-reference symfony doctrine-orm

我在'父'映射的实体(用户)上有一个自引用的一对多关联,并由'children'反转.我希望能够删除不是父母的用户.我的实体声明如下.

class User implements UserInterface
{
   /**
    * @ORM\Column(name="id", type="smallint")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
   protected $id;

   (...)

   /**
    * @ORM\OneToMany(targetEntity="User", mappedBy="parent")
    */
   protected $children;

   /**
    * @ORM\ManyToOne(targetEntity="User", inversedBy="children")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
    */
   protected $parent;

   public function __construct()
   {
       $this->parentId = null; // Default value for column parent_id
       $this->children = new ArrayCollection();
   }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试删除不是父项的子用户时,我收到以下错误.

带有消息'SQLSTATE [23000]的异常'PDOException':完整性约束违规:1451无法删除或更新父行:外键约束失败

我尝试过级联删除,如下所示.

/**
 * @ORM\OneToMany(targetEntity="User", mappedBy="parent", cascade={"persist", "remove"})
 */
protected $children;
Run Code Online (Sandbox Code Playgroud)

无论如何都会得到同样的错误.有帮助吗?

Zel*_*jko 9

用这个:

/**
* @ORM\ManyToOne(
*     targetEntity="User", 
*     inversedBy="children", 
*     cascade={"persist", "remove"}
* )
*
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
Run Code Online (Sandbox Code Playgroud)

是什么onDelete="SET NULL"做的是,当你删除一个父类,子元素将获得PARENT_ID列NULL值.这发生在数据库级别,因此您必须学习:schema:update.