當我運行這個問題時,我所做的是編寫一個函數,它動態讀取對象的元數據,遍歷它們並手動複製每個字段。
元數據將有一個名爲「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));
}
}
希望這會有所幫助。
檢查這[問題](http://stackoverflow.com/questions/14158111/deep-clone-doctrine-entity-with-related-entities) – pazulx
我試過了,但它不起作用。結果是一樣的。 – Angel