doctrine2删除ManyToMany关系

时间:2010-09-07 02:03:26

标签: php doctrine many-to-many doctrine-orm

我有一个具有以下类成员和映射的Group Entity:

/**
 * @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);
    }
}

删除孩子:

???????

我该如何移除孩子?

3 个答案:

答案 0 :(得分:4)

当Doctrine从关系中检索值列表时,它使用ArrayCollection的实例而不是常规数组。

ArrayCollection实现了ArrayAccess,这意味着unset可以正常工作。

然而,更简单的方法是:

   $this->getChildren()->removeElement($child) // to remove by object
   $this->getChildren()->remove($index) // to remove by array index

虽然,我对你当前的例子有点困惑。为什么假设在连接表中Child ID和Group id应该相同?您在添加示例中为什么要将$group添加到$children[]数组?并不意味着要批评,但它会使解析你的意图变得困难。

答案 1 :(得分:0)

public function removeChild(Group $group)
{
    foreach ($this->getChildren() as $key => $child)
    {
        if ($child->getId() == $group->getId())
            unset($this->children[$key]);
            break;
    }
}

这很有效。这是最有效的方式吗?

答案 2 :(得分:0)

使用ArrayCollection :: removeElement

相关问题