我将以下代码用于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;
}
Controller :
$entity->addSyncSchema($container);
$em->flush();
现在,我如何使用它来删除关系?是否需要向我的实体添加诸如removeSyncSchema()的方法?那会是什么样?
最佳答案
您正在这里寻找 ArrayCollection::removeElement
方法。
public function removeSchema(SchemaInterface $schema)
{
$this->schemata->removeElement($schema)
return $this;
}
提示:
您可以使用
ArrayCollection::add
将元素添加到现有集合中。哎呀。在某些情况下,您可能还想在添加元素之前检查它是否已经包含该元素。
public function addSchema(SchemaInterface $schema)
{
if (!$this->schemata->contains($schema)) {
$this->schemata->add($schema);
}
return $this;
}
关于php - Symfony2 : How to remove an element from a Doctrine ArrayCollection (many-to-many relation)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21995666/