Symfony2:如何从Doctrine ArrayCollection中删除元素(多对多关系)?

Mat*_*der 10 php database doctrine arraycollection symfony

我在symfony2(doctrine)中使用以下代码作为我的多对多关系

实体:

/**
 * @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;
}
Run Code Online (Sandbox Code Playgroud)

控制器:

$entity->addSyncSchema($container);
$em->flush();
Run Code Online (Sandbox Code Playgroud)

现在,我该如何使用它来删除关系?我是否需要向我的实体添加方法,如removeSyncSchema()?那会是什么样的?

Nic*_*ich 22

你在ArrayCollection::removeElement这里寻找方法.

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

    return $this;
}
Run Code Online (Sandbox Code Playgroud)

小费:

您可以使用ArrayCollection::add向现有集合添加元素.OOP.

在某些情况下,您可能还想在添加元素之前检查已包含元素.

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

    return $this;
}
Run Code Online (Sandbox Code Playgroud)