mvm*_*oay 6 php entity symfony doctrine-orm
我试图将实体对象克隆到Symfony 2/Doctrine中的另一个表.知道怎么做吗?
从数据库中检索对象后,我可以像这样克隆它:
$newobject = clone $oldbject;
Run Code Online (Sandbox Code Playgroud)
这给了我一个新对象,我可以将其作为新记录保存到数据库中的同一个表中.其实我不想这样做.我想将对象存储到数据库中的不同表中.但要做到这一点,我将不得不改变父实体,对吗?怎么做到这一点?
但那时你并没有真正克隆一个实体.实际上,您需要一个不同的实体.这两个实体是什么样的?他们有相同的领域吗?你可以这样做:
$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));
}
}
Run Code Online (Sandbox Code Playgroud)
这是未经测试的 - 可能有一两个错误,但这应该允许将所有属性从一个对象复制到另一个对象(假设这两个对象上的属性具有相同的名称).
| 归档时间: |
|
| 查看次数: |
3086 次 |
| 最近记录: |