Symfony2实体克隆不起作用

时间:2013-10-25 14:00:55

标签: symfony doctrine-orm entity clone

我喜欢在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'

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

很可能克隆的实体应与ORM分离。

你可以尝试吗

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

$cloneEntity = clone $entity;

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

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

答案 1 :(得分:0)

您还需要克隆子实体。

尝试在您的父实体上添加此方法:

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