2010-09-07 140 views
0

我有一个集团与下面的类成员和映射: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); 
    } 
} 

删除子:

??????? 

我会如何移除一个孩子?

回答

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[]阵列?不要意味着批评,但它会使你的意图难以解析。

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

This works。它是最有效的方式吗?

0

使用ArrayCollection :: removeElement