gpt4 book ai didi

mysql - 在 sonata admin 自定义克隆操作中强制自动递增 id

转载 作者:行者123 更新时间:2023-11-29 01:57:52 24 4
gpt4 key购买 nike

我正在 sonata admin 中进行克隆操作——遵循 Sonata 文档的建议:

<?php // src/Acme/DemoBundle/Controller/CRUDController.php

namespace Acme\DemoBundle\Controller;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sonata\AdminBundle\Controller\CRUDController as Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CRUDController extends Controller
{
public function cloneAction()
{
$id = $this->get('request')->get($this->admin->getIdParameter());

$object = $this->admin->getObject($id);

if (!$object) {
throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
}

$clonedObject = clone $object;
$clonedObject->setName($object->getName()." (Clone)");

$this->admin->create($clonedObject);

$this->addFlash('sonata_flash_success', 'Cloned successfully');

return new RedirectResponse($this->admin->generateUrl('list'));
}
}

在 $clonedobject 上设置一个 id 后,我得到一个 DBAL 异常。不允许具有相同 ID 的主键--

我试过设置一个唯一的id

没有 id 希望我的模式中的自动递增会强制++

谢谢你的帮助

最佳答案

Geert 是对的,将 id 设置为 null 是符合 Doctrine 的方法。

但是,您不必在您的对象中实现 setId 方法,您也可以重写 __clone 方法,如下所示:

public function __clone()
{
parent::__clone();
$this->id = null;
$this->name .= " (Clone)";
}

参见 How to re-save the entity as another row in Doctrine 2

关于mysql - 在 sonata admin 自定义克隆操作中强制自动递增 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com