假设我有实体 $e。是否有任何通用的方法来存储它作为另一行,其中将有相同的实体数据,但另一个主键?
$e
为什么我需要这样做: 我实现了某种 时间数据库模式,而不是更新行,我只需要创建另一个。
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();
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
__clone()
$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.
$new
I would still null the ID property via the __clone() method as it makes sense from a pure model view.
Digging into the Doctrine code, this is because the generated proxy classes implement __clone() with this important line
unset($this->_entityPersister, $this->_identifier);
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
Copying the data in a new Object of the same class and persisting it will do. Keep it simple!