Doctrine2删除Manytomany关系
-
01-10-2019 - |
题
我有一个与以下类成员和映射的团体实体:
/**
* @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);
}
}
去除孩子:
???????
我将如何去除孩子?
解决方案
当教义从关系中检索值列表时,它使用 ArrayCollection 而不是常规阵列。
ArrayCollection实现了ArrayAccess,这意味着 unset
工作正常。
但是,更简单的方法是:
$this->getChildren()->removeElement($child) // to remove by object
$this->getChildren()->remove($index) // to remove by array index
虽然,我对您当前的示例有些困惑。您为什么假设子ID和组ID在联接表中应该相同?为什么在您的添加示例中添加 $group
到 $children[]
大批?并不意味着要批评,但这会使您的意图变得困难。
其他提示
public function removeChild(Group $group)
{
foreach ($this->getChildren() as $key => $child)
{
if ($child->getId() == $group->getId())
unset($this->children[$key]);
break;
}
}
这有效。这是最有效的方法吗?
使用ArrayCollection :: removelement
不隶属于 StackOverflow