php 如何将实体重新保存为 Doctrine 2 中的另一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9071094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:05:52  来源:igfitidea点击:

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

phpdoctrinedoctrine-ormtemporal-database

提问by zerkms

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?

假设我有 entity $e。是否有任何通用方法将其存储为另一行,该行将具有相同的实体数据但另一个主键?

Why I need this: I'm implementing some sort of Temporal Databaseschema and instead of updating the row I just need to create another one.

为什么我需要这个:我正在实施某种临时数据库模式,而不是更新行,我只需要创建另一个。

回答by Phil

Try cloning and add the following method to your entity

尝试克隆并将以下方法添加到您的实体

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

You may need to detachthe 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

刚刚尝试使用一个简单的 SQLite 演示。你不应该需要做任何事情。以下内容对我有用,无需添加__clone()方法或做任何其他不寻常的事情

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

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

一旦刷新,$new实体就有了一个新 ID 并在数据库中保存为新行。

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

我仍然会通过该__clone()方法将 ID 属性设为空,因为从纯模型视图来看它是有意义的。

Update 2

更新 2

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

深入研究 Doctrine 代码,这是因为生成的代理类实现__clone()了这一重要行

unset($this->_entityPersister, $this->_identifier);

回答by redolent

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

这是我使用的一个简单的策略,它不涉及过多的复杂性:

$new->fromArray( $old->toArray() );
$new->id = NULL;