2013-10-25 151 views
1

我喜歡克隆Symfony2中的實體。如果我克隆實體是小孩的實體,它工作正常。以下代碼不起作用。它克隆的實體,但我得到一個重複鍵錯誤Symfony2實體克隆不起作用

代碼在我的控制器:

$id = $request->get('id'); 
$entity = $orSessionVersionRepository->find($id); 
// A new Version must be created! 
// Clone OrSessionVersion entity 
$cloneEntity = clone $entity; 
$em->persist($cloneEntity); 
$em->flush(); 

錯誤:

An exception occurred while executing 'INSERT INTO or_session_version (version, name, duration, occupancy_standard, condition_weekday, condition_start, condition_end, creator, remarks, edit_reason, min_age, max_age, status, type, color, created, modified, or_session_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [2, "Session 1", "04:00:00", "75", "a:7:{i:0;i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;}", "08:00:00", "16:30:00", "admin", null, null, 16, 100, "final", "default", "#1429e6", "2013-10-25 14:25:14", "2013-10-25 14:25:14", "41"]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2-41' for key 'or_session_id_version' 

有人能幫忙嗎?

+0

爲什麼你需要克隆的實體? –

+0

「$ em-> persist($ entity);」工作嗎? – goto

+1

您需要取消設置ID或其他獨特屬性,否則會遇到約束衝突。 – busypeoples

回答

0

您還需要克隆子實體。

嘗試添加這種方法對你父實體:

public function __clone() { 
    if ($this->id) { 
     $this->child = clone $this->child; 
    } 
} 
0

最有可能克隆的實體應與ORM分離。

你可以嘗試做

$id = $request->get('id'); 
$entity = $orSessionVersionRepository->find($id); 

$cloneEntity = clone $entity; 

$em->detach($cloneEntity); 
$cloneEntity->setId(null); 

$em->persist($cloneEntity); 
$em->flush(); 
+0

此解決方案不起作用。我克隆了超過1個動作的實體,並且它工作正常。我在每個實體中實現了一個__clone公共函數,以便將關係克隆到。有沒有可能克隆功能不起作用,因爲教義給出一個代理對象,而不是真實的對象? –