0

我有一个具有以下类成员和映射的组实体:

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

删除一个孩子:

???????

我将如何删除一个孩子?

4

3 回答 3

4

当 Doctrine 从关系中检索值列表时,它使用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[]数组中?并不意味着要批评,但这会使解析您的意图变得困难。

于 2010-09-07T20:43:51.123 回答
0

使用 ArrayCollection::removeElement

于 2011-12-05T14:17:12.037 回答
0
public function removeChild(Group $group)
{
    foreach ($this->getChildren() as $key => $child)
    {
        if ($child->getId() == $group->getId())
            unset($this->children[$key]);
            break;
    }
}

这行得通。这是最有效的方法吗?

于 2010-09-07T02:42:51.667 回答