【问题标题】:doctrine 2 cascade persist saving too much学说2级联坚持节省太多
【发布时间】:2015-10-30 18:50:30
【问题描述】:

所以这是我在 EventListener 上的 prePersist

public function prePersist(LifecycleEventArgs $args)
    {
        //the first entity will have the PMP, so we catch it and continue to skip this if after this
        if ($this->pmp == null) {
            $this->pmp = $args->getEntity()->getPmp();
        }

        $taxonomicClass = $args->getEntity();

        if($taxonomicClass instanceof TaxonomicClass){

            if(is_null($taxonomicClass->getId())){
                //here it says that i have created a new entity, need to persist it via cascade={"persist"}
                $taxonomicClass->setPmp($this->pmp);
            }
        }
    }

没关系,我已经在上面添加了注释:

 /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Pmp", cascade={"persist"})
     * @ORM\JoinColumn(name="pmp_id", referencedColumnName="id", nullable=false)
     **/
    private $pmp;

它保存了我的层次结构中的所有内容,甚至是一个新的 PMP,一个已经存在于数据库中的对象!

我想要的是我从我的层次结构中保存的所有内容都需要与我通过的 PMP 相关,但是当我设置 $taxonomicClass->setPmp($this->pmp); 学说时认为我创建了一个新的 PMP 实例,因为我没有,我只是希望这家伙与 PMP 有联系。

我尝试将merge 放在级联选项上,但它仅适用于persist,如何使学说不创建新实例,而是使用我通过的那个?

【问题讨论】:

    标签: php symfony doctrine-orm cascade persist


    【解决方案1】:

    注意到我的问题,我正在从内存中分配一个属性,我应该将他从数据库中检索到教义理解。

    public function prePersist(LifecycleEventArgs $args)
    {
        if ($this->pmp == null) {
                $this->pmp = $args->getEntity()->getPmp();
        }
    
        $taxonomicClass = $args->getEntity();
    
        if($taxonomicClass instanceof TaxonomicClass){
    
            if(is_null($taxonomicClass->getId())){
                //this solved the problem
                $pmp = $args->getEntityManager()->getRepository("AppBundle:Pmp")->find($this->pmp->getId());
                $taxonomicClass->setPmp($pmp);
            }
        }
    }
    

    我现在要记住,当创建一个新实体但不需要保存它时,您必须从 db 中检索它,cascade={"persist"} 甚至没有必要

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多