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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度