Doctrine 2.4不删除孤立的奴隶ManyToMany关系对象

时间:2014-03-07 09:52:54

标签: doctrine-orm

有人会指出为什么orphanRemoval不能用于以下ManyToMany关系吗?

我的意思是,中间的many_to_many表会创建/更新/删除其行,但是end / slave表不会删除孤立行。

非常感谢,继承人是我的映射

    Class TaskRecursive
    {
        /**
         * @Assert\Valid
         * @ORM\ManyToMany( targetEntity="TaskAttachment", inversedBy="tasks", cascade={ "persist" }, orphanRemoval=true, fetch="EAGER" )
         * @ORM\JoinTable(
         *      name="tasks_attachments",
         *      joinColumns={@ORM\JoinColumn(name="task_id", referencedColumnName="id", onDelete="CASCADE" )},
         *      inverseJoinColumns={@ORM\JoinColumn(name="task_attachment_id", referencedColumnName="id")}
         * )
         */
        private $tasksAttachmentsTask;


    Class TaskAttachment
    {
        /**
         * @ORM\ManyToMany( targetEntity="TaskRecursive", mappedBy="tasksAttachmentsTask" )
         */
        private $tasks;

注意我没有使用cascade = {“remove”},因为我不希望在删除拥有的对象时删除反向对象,我希望当它与拥有没有更多关系时删除反向对象侧面物体。

替代方法: 在我的控制器中,我明确地调用$taskRecursive->setTasksAttachmentsTask( $taskAttachments )来替换整个集合,因此我编辑了该方法以手动删除孤立集合的对象:

    /**
     * Set tasksAttachmentsTask
     *
     * @param \Doctrine\Common\Collections\ArrayCollection $taskAttachmentsTask
     * @return TaskRecursive
     */
    public function setTasksAttachmentsTask( \Doctrine\Common\Collections\ArrayCollection $taskAttachments )
    {
        if( $taskAttachments != $this->tasksAttachmentsTask )
        {
            foreach( $taskAttachments as $tasAttachment )
            {
                $tasAttachment->addTaskRecursive( $this );
            }
            $this->_onPropertyChanged( 'tasksAttachmentsTask', $this->tasksAttachmentsTask, $taskAttachments );

            //Orphan removal is not working fine, so le'ts removed orphan objects by hand
            foreach( $this->tasksAttachmentsTask as $ta )
            {
                if( !$taskAttachments->contains( $ta ) && $ta->getTasks()->count()  < 2 )
                {
                    $this->tasksAttachmentsTask->removeElement( $ta );
                }
            }

            $this->tasksAttachmentsTask = $taskAttachments;
        }

        return $this;
    }

0 个答案:

没有答案