如何在Doctrine 2中重新保存实体作为另一行 [英] How to re-save the entity as another row in Doctrine 2
问题描述
$ e
。有没有任何通用的方式存储它作为另一行,它将具有相同的实体数据,但另一个主键? 为什么我需要这个:我正在实现一些排序时态数据库模式,而不是更新行只需要创建另一个。
尝试克隆并将以下方法添加到您的实体中
public function __clone(){
$ this-> id = null;
}
您可能需要 detach 实体,然后再继续存在。我没有我的开发机器现在可以测试这个。
$ f = clone $ e;
$ em-> detach($ f);
$ em-> persist($ f);
$ em-> flush();
更新
SQLite演示。你不应该做任何事情。以下工作对我来说没有添加 __ clone()
方法或做任何其他的一般的
$ new = clone $ old;
$ em-> persist($ new);
$ em-> flush();
一旦刷新, $ new
一个新的ID,并被保存为DB中的一个新行。
我仍然会通过 __ clone()
方法,因为它是纯粹的模型视图。
更新2
挖掘Doctrine代码,这是因为生成的代理类使用这个重要行实现 __ clone()
unset($ this-> _entityPersister,$ this-> _identifier);
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 need this: I'm implementing some sort of Temporal Database schema and instead of updating the row I just need to create another one.
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);
这篇关于如何在Doctrine 2中重新保存实体作为另一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!