doctrine2 删除多对多关系
我有一个具有以下类成员和映射的组实体:
/**
* @ManyToMany(targetEntity="Group", cascade={"persist"})
* @JoinTable(name="groups_children",
* joinColumns={@JoinColumn(name="group_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="child_id", referencedColumnName="id", unique=true)}
* )
*/
private $children;
添加子项很简单:
public function addChild(Group $group)
{
if (! $this->hasChild($group)) {
$this->children[] = $group;
App::getEntityManager()->persist($this);
}
}
删除子项:
???????
如何删除子项?
I have a Group Entity with the following class member and mapping:
/**
* @ManyToMany(targetEntity="Group", cascade={"persist"})
* @JoinTable(name="groups_children",
* joinColumns={@JoinColumn(name="group_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="child_id", referencedColumnName="id", unique=true)}
* )
*/
private $children;
Adding a child is trivial:
public function addChild(Group $group)
{
if (! $this->hasChild($group)) {
$this->children[] = $group;
App::getEntityManager()->persist($this);
}
}
Removing a child:
???????
How would I remove a child?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当 Doctrine 从关系中检索值列表时,它使用 ArrayCollection< 的实例/a> 与常规数组相反。
ArrayCollection 实现了 ArrayAccess,这意味着
unset
可以正常工作。然而,一种更简单的方法是:
尽管,我对您当前的示例有点困惑。为什么假设连接表中的子 ID 和组 ID 应该相同?为什么在添加示例中将
$group
添加到$children[]
数组中?无意批评,但这会让解析你的意图变得困难。When Doctrine retrieves a list of values from a relationship, it uses an instance of ArrayCollection as opposed to a regular array.
ArrayCollection implements ArrayAccess, which means that
unset
works just fine.However, an simpler way of doing it would be:
Although, I'm a little confused with your current example. Why are you assuming that the Child id and Group id should be identical in the join table? And why in your adding example are you adding
$group
to the$children[]
array? Don't mean to be critical, but it makes parsing your intention difficult.这有效。但这是最有效的方法吗?
This works. Is it the most efficient way though?
使用 ArrayCollection::removeElement
Use ArrayCollection::removeElement