symfony - 从具有自引用一对多关联的实体中删除子项

标签 symfony doctrine-orm mapping self-reference

我在实体(用户)上有一个自引用的一对多关联,该实体(用户)由“父级”映射并由“子级”反转。我希望能够删除不是 parent 的用户。我的实体声明如下。

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();
   }
}

当我尝试删除不是父级的子用户时,出现以下错误。

exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

我尝试过进行级联删除,如下。

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

无论哪种方式都会出现相同的错误。有什么帮助吗?

最佳答案

使用这个:

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

onDelete="SET NULL" 的作用是,当您删除父元素时,其子元素将在parent_id 列中获得 NULL 值。这种情况发生在数据库级别,因此您必须教条:架构:更新。

关于symfony - 从具有自引用一对多关联的实体中删除子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13046810/

相关文章:

php - ManyToMany Doctrine 与 FOSUserBundle 的关系

c++ - 映射不同类型的 vector 指针

database - 如何解决这个SQLSTATE[HY000] [2002] no connection could be because the target machine actively refused

php - Symfony3 : is it possible to change the name of a form?

php - 与 symfony 2.3 中的 Doctrine 的多重联系

php - 订单日期查询,语法错误

php - Doctrine 中的多个 ManyToOne 关系

java - mappedBy 引用未知的目标实体属性 - hibernate 错误

ios - 我如何访问其他 Mappble 类对象的值。(Alamofire Object Mapper)

arrays - Twig 中的输出数组