문제

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?

도움이 되었습니까?

해결책

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:

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

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.

다른 팁

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

This works. Is it the most efficient way though?

Use ArrayCollection::removeElement

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top