1

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

有人可以帮忙吗?

4

2 回答 2

0

克隆实体很可能应该从 ORM 中分离出来。

你能试着做吗

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

$cloneEntity = clone $entity;

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

$em->persist($cloneEntity);
$em->flush();
于 2013-10-25T14:22:49.030 回答
0

您还需要克隆子实体。

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

public function __clone() {
    if ($this->id) {
        $this->child = clone $this->child;
    }
}
于 2014-04-23T12:18:33.857 回答