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

1

10

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?

Pompon answered 24/2, 2014 at 18:12 Comment(2)
Are you not doing doctrine:generate entities ?Stretcher
oh... usually dont, but tried it and sure enough... thanks.Pompon
E
23

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;
}
Esp answered 24/2, 2014 at 22:13 Comment(1)
nice answer. +1 for checking before addingParsimony

© 2022 - 2024 — McMap. All rights reserved.