gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:56:25 25 4
gpt4 key购买 nike

我在实体(用户)上有一个自引用的一对多关联,该实体(用户)由“父级”映射并由“子级”反转。我希望能够删除不是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com