[英]Remove element from collection in Doctrine2
I have a Command
entity which has an:m relationship with Alias
. 我有一个
Command
实体,它与Alias
有一个:m关系。 This is a piece of code of the Command
class: 这是
Command
类的一段代码:
class Command
{
...
/**
* @ORM\ManyToMany(targetEntity="Alias", inversedBy="alias_command", cascade={"persist", "remove"})
* @ORM\JoinTable(name="command_has_alias",
* joinColumns={@ORM\JoinColumn(name="command_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="alias_id", referencedColumnName="id")}
* )
*/
protected $command_alias;
public function __construct()
{
$this->command_alias = new ArrayCollection();
}
...
/**
* Add alias to command.
* @param Alias $alias
*/
public function addCommandAlias(Alias $alias)
{
$this->command_alias[] = $alias;
}
/**
* Get alias from command.
* @return Doctrine\Common\Collections\Collection
*/
public function getCommandAlias()
{
return $this->command_alias;
}
/**
* Remove alias from command.
* @param Alias $alias
*/
public function removeCommandAlias(Alias $alias)
{
$this->command_alias->removeElement($alias);
return $this;
}
}
I want to delete an element from the collection (association in n:m intermediary table) but what I have is the ID of the Alias
. 我想从集合中删除一个元素(n:m中间表中的关联),但是我拥有的是
Alias
的ID。 I read Doctrine docs around Removing associations but is not clear to me how to delete the element from the collection. 我阅读了有关删除关联的 Doctrine文档,但对我不清楚如何从集合中删除元素。 I don't know if remove by key is the path to follow here or if I can do something in my entity to get this easy anyway I will not remove the
Command
and either the Alias
I just want to remove the relation between them. 我不知道按键删除是这里要遵循的路径,还是无论如何我都可以在实体中执行某些操作以轻松实现此目的,所以我不会删除
Command
而我只是想删除它们之间的关系的Alias
。 Any advice? 有什么建议吗?
This should be pretty straigthforward. 这应该很简单。 If all you need to do is remove relation between an alias and a command, while having alias ID, add following method to Command:
如果您需要做的就是删除别名和命令之间的关系,同时拥有别名ID,请向Command添加以下方法:
public function removeAliasById($aliasId)
{
foreach ($this->command_alias as $alias) {
if ($alias->getId() == $aliasId) {
$this->command_alias->removeElement($alias);
return;
}
}
}
When you have that, removing alias from command by id is: 有了这个名称后,按id从命令中删除别名是:
$command->removeAliasById($aliasId);
$entityManager->persist($command);
$entityManager->flush();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.