How to re-save the entity as another row in Doctrine 2

后端 未结 3 1838
眼角桃花
眼角桃花 2020-11-28 04:55

Let\'s say I have entity $e. Is there any generic way to store it as another row, which would have the same entity data but another primary key?

Why I n

相关标签:
3条回答
  • 2020-11-28 05:26

    I just do:

    /**
     * __clone
     *
     * @return void
     */
    public function __clone()
    {
        $this->id = null;
    }
    

    More details here https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/cookbook/implementing-wakeup-or-clone.html

    0 讨论(0)
  • 2020-11-28 05:37

    Here's a simple strategy I used that doesn't involve excessive complexity:

    $new->fromArray( $old->toArray() );
    $new->id = NULL;
    
    0 讨论(0)
  • 2020-11-28 05:40

    Try cloning and add the following method to your entity

    public function __clone() {
        $this->id = null;
    }
    

    You may need to detach the entity before persisting it. I don't have my dev machine handy to test this right now.

    $f = clone $e;
    $em->detach($f);
    $em->persist($f);
    $em->flush();
    

    Update

    Just tried using a simple SQLite demo. You shouldn't need to do anything. The following worked for me without adding a __clone() method or doing anything else out of the ordinary

    $new = clone $old;
    $em->persist($new);
    $em->flush();
    

    Once flushed, the $new entity had a new ID and was saved as a new row in the DB.

    I would still null the ID property via the __clone() method as it makes sense from a pure model view.

    Update 2

    Digging into the Doctrine code, this is because the generated proxy classes implement __clone() with this important line

    unset($this->_entityPersister, $this->_identifier);
    
    0 讨论(0)
提交回复
热议问题