2014-04-30 71 views
0

我需要克隆一個名爲Projects的實體,並使用2個實體關係調用ZoneSector。 我已經嘗試過使用類似的東西在控制器:如何克隆實體間關係?

$new_project = clone $project; 
$em = $this->getDoctrine()->getManager(); 
$em->persist($new_project); 
$em->flush(); 

它適用於複製實體項目,但它不會複製其他2個實體及其關係......

任何建議?

編輯:我在這question發現了一個快速和簡單的解決方案。謝謝!

+0

檢查這[問題](http://stackoverflow.com/questions/14158111/deep-clone-doctrine-entity-with-related-entities) – pazulx

+0

我試過了,但它不起作用。結果是一樣的。 – Angel

回答

0

試試這個功能:

public static function cloneObject($source) { 
    if ($source === null) { 
     return null; 
    } 

    return unserialize(serialize($source)); 
} 

我用它來克隆實體在ZF2項目,並能正常工作。它允許我遍歷主實體中的一對多關聯實體。

1

當我運行這個問題時,我所做的是編寫一個函數,它動態讀取對象的元數據,遍歷它們並手動複製每個字段。

元數據將有一個名爲「fieldNames」的屬性與非關係字段,以及「associationMappings」與關係字段。一個例子:

$em = $this->getDoctrine()->getManager(); 
    $objectToClone = $em->getRepository('Xxx')->find(xx); 
    $class = get_class($objectToClone); 
    $metadata = $em->getMetadataFactory()->getMetadataFor($class); 
    // Symfony\Component\PropertyAccess\PropertyAccessor; 
    $accessor = new PropertyAccessor(); 
    $newObject = new Xxx(); 
    foreach ($metadata->getFieldNames() as $value) { 
     if (property_exists($objectToClone, $value)) { 
      $accessor->setValue($newObject, $value, $accessor->getValue($objectToClone, $value)); 
     } 
    } 
    foreach ($metadata->getAssociationMappings() as $key => $value) { 
     if (property_exists($objectToClone, $key)) { 
      $accessor->setValue($newObject, $key, $accessor->getValue($objectToClone, $key)); 
     } 
    } 

希望這會有所幫助。