重载对象的__clone方法以将其ID设置为null


Overload the __clone method of an object to set its ID to null

我想克隆对象并在数据库中保存一个副本,但问题是ID需要重置为null,以便它可以在数据库中获得自动序列号。

我正在使用Doctrine和Symfony2。我明白我需要修改我的实体的__clone方法,但我不知道如何在其中插入什么。

我有一个基本的克隆操作:

public function cloneAction()
{
    $object = $this->admin->getSubject();
    if (!$object) {
        throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
    }
    // Be careful, you may need to overload the __clone method of your object
    // to set its id to null !
    $clonedObject = clone $object;
    $this->admin->create($clonedObject);
    $this->addFlash('sonata_flash_success', 'Cloned successfully');
    return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters()));
}

Sonata的文档说我必须这样做,但是我以前从来没有使用过__clone,而且我是PHP的新手。

没有问题。无论如何,都没有必要重载__clone方法。我所要做的就是修复我的实体映射,它工作了。