drbmhd9583 2016-01-02 04:48
浏览 54
已采纳

从Doctrine2中的集合中删除元素

I have a Command entity which has a n:m relationship with Alias. This is a piece of code of the Command class:

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. I read Doctrine docs around Removing associations but is not clear to me how to delete the element from the collection. 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. Any advice?

  • 写回答

1条回答 默认 最新

  • dongya5893 2016-01-02 05:42
    关注

    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:

    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:

    $command->removeAliasById($aliasId);
    $entityManager->persist($command);
    $entityManager->flush();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示