【问题标题】:Clone doctrine entity with related one to many entity克隆具有相关一对多实体的学说实体
【发布时间】:2018-10-04 11:44:23
【问题描述】:

我创建了一个名为 Landing 的实体,它与 LandingContent 具有 OneToMany 关系。一个登陆可以有一个或多个内容。

我需要克隆这个 Landing 实体并在数据库中设置新的 ID。 (这工作正常)。我还需要克隆具有新 ID 的 LandingContent。

Landing中的clone方法是这样的:

 /**
     * Clones the Landing
     */
    public function __clone()
    {
        $this->id = null;
        $this->title = new LandingTitle('Copia de ' . $this->getTitle()->getValue());

        $contents = $this->getContents();
        $this->contents = new ArrayCollection();
        if(count($contents) > 0){
            foreach ($contents as $content) {
                $cloneContent = clone $content;
                $this->contents->add($cloneContent);
            }
        }
    }

实际上代码用新的 Landingitle 在 Landing 表中创建了一条新记录,并克隆了内容,但在同一个 Landing 中,而不是在克隆的 Landing 中。

任何帮助将不胜感激。(我也在尝试修复它在 SO 上的其他问题中搜索)。

【问题讨论】:

    标签: php symfony doctrine clone


    【解决方案1】:

    您必须在内容中添加一个 setter 以将它们链接到新的 Landing:

    /**
     * Clones the Landing
     */
    public function __clone()
    {
        $this->id = null;
        $this->title = new LandingTitle('Copia de ' . $this->getTitle()->getValue());
    
        $contents = $this->getContents();
        $this->contents = new ArrayCollection();
        if(count($contents) > 0){
            foreach ($contents as $content) {
                $cloneContent = clone $content;
                $cloneContent->setLanding($this);
                $this->contents->add($cloneContent);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-09
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      相关资源
      最近更新 更多