![](/img/trans.png)
[英]Symfony2 : Doctrine - Update table structure on two different entity managers
[英]Symfony 2 - Clone entity to different table
我試圖將實體對象克隆到Symfony 2 / Doctrine中的另一個表。 知道怎么做嗎?
從數據庫中檢索對象后,我可以像這樣克隆它:
$newobject = clone $oldbject;
這給了我一個新對象,我可以將其作為新記錄保存到數據庫中的同一個表中。 其實我不想這樣做。 我想將對象存儲到數據庫中的不同表中。 但要做到這一點,我將不得不改變父實體,對嗎? 怎么做到這一點?
但那時你並沒有真正克隆一個實體。 實際上,您需要一個不同的實體。 這兩個實體是什么樣的? 他們有相同的領域嗎? 你可以這樣做:
$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));
}
}
這是未經測試的 - 可能有一兩個錯誤,但這應該允許將所有屬性從一個對象復制到另一個對象(假設這兩個對象上的屬性具有相同的名稱)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.