6

我正在尝试将实体对象克隆到 Symfony 2 / Doctrine 中的不同表中。知道怎么做吗?

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

$newobject = clone $oldbject;

这给了我一个新对象,我可以将它作为新记录保存到数据库中的同一个表中。其实我不想这样做。我想将对象按原样存储到数据库中的不同表中。但要做到这一点,我必须更改父实体,对吗?如何做到这一点?

4

1 回答 1

9

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

$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));
    }
}

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

于 2013-01-08T13:51:21.217 回答