Symfony2: How to remove an element from a Doctrine ArrayCollection (many-to-many relation)?

Matt Welander picture Matt Welander · Feb 24, 2014 · Viewed 19.5k times · Source

I use the following code for my many-to-many relation in symfony2 (doctrine)

Entity:

/**
 * @ORM\ManyToMany(targetEntity="BizTV\ContainerManagementBundle\Entity\Container", inversedBy="videosToSync")
 * @ORM\JoinTable(name="syncSchema")
 */
private $syncSchema;

public function __construct()
{
    $this->syncSchema = new \Doctrine\Common\Collections\ArrayCollection(); 
}

public function addSyncSchema(\BizTV\ContainerManagementBundle\Entity\Container $syncSchema)
{
    $this->syncSchema[] = $syncSchema;
}

Controller:

$entity->addSyncSchema($container);
$em->flush();

Now, how can I use this to remove a relation? Do I need to add a method to my entity like removeSyncSchema()? What would that look like?

Answer

Nicolai Fröhlich picture Nicolai Fröhlich · Feb 24, 2014

You're looking for the ArrayCollection::removeElement method here.

public function removeSchema(SchemaInterface $schema)
{
    $this->schemata->removeElement($schema)

    return $this;
}

tip:

You can use ArrayCollection::add to add elements to an existing collection. OOP.

In some cases you may also want to check wether already contains the element before adding it.

public function addSchema(SchemaInterface $schema)
{
    if (!$this->schemata->contains($schema)) {
        $this->schemata->add($schema);
    }

    return $this;
}