Symfony 2 - 克隆实体到不同的表 [英] Symfony 2 - Clone entity to different table

查看:49
本文介绍了Symfony 2 - 克隆实体到不同的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将实体对象克隆到Symfony 2 / Doctrine中的不同表中。任何想法如何做到这一点?

I am trying to clone an entity-object to a different table in Symfony 2 / Doctrine. Any idea how to do this?

从数据库检索对象后,我可以像这样克隆:

After retrieving the object from the database I can clone it like this:

$newobject= clone $oldbject;

这给了我一个新的对象,我可以坚持作为新的记录在同一个表中数据库。其实我不想这样做我想将对象存储在数据库中的另一个表中。但是要做到这一点,我必须改变父实体吗?如何实现这一点?

This gives me a new object, which I can persist as a new record to the same table in the database. Actually I dont want to do this. I want to store the object as it is to a different table in the database. But to do this, I would have to change the parent entity, right? How to achieve this?

推荐答案

但是,你不是真的克隆一个实体。其实你想要一个不同的实体。这两个实体是什么样的?他们有相同的领域吗?你可以这样做:

But then you're not really cloning an entity. In fact, you want a different entity. What do the two entities look like? Do they have the same fields? You could do something like this:

$oldEntity = $oldEntity;
$newEntity = new NewEntity();
$oldReflection = new \ReflectionObject($oldEntity);
$newReflection = new \ReflectionObject($newEntity);

foreach ($oldReflection->getProperties() as $property) {
    if ($newReflection->hasProperty($property->getName())) {
        $newProperty = $newReflection->getProperty($property->getName());
        $newProperty->setAccessible(true);
        $newProperty->setValue($newEntity, $property->getValue($oldEntity));
    }
}

这是未经测试的 - 可能有错误或两个,但这应该允许将所有属性从一个对象复制到另一个对象(假设两个对象上的属性具有相同的名称)。

This is untested - and may have an error or two, but this should allow all properties to be copied from one object to another (assuming the properties have the same name on both objects).

这篇关于Symfony 2 - 克隆实体到不同的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆