mysql - 在sonata管理自定义克隆操作中强制自动递增ID

标签 mysql symfony doctrine-orm sonata-admin symfony-sonata

我正在 Sonata 管理中进行克隆操作 - 遵循 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管理自定义克隆操作中强制自动递增ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415376/

相关文章:

mysql - 与表的多个内部联接

php - Symfony 查询生成器 : too many queries

php - Doctrine 实体管理器导致页面中断

php - 内部连接原则

python - mysql 如何对文本数据进行排序?

php - Mysql 出现套接字故障

php - 使用 Laravel Eloquent 处理对话

symfony - Hwi oauth bundle 和 Symfony 3.4 无法 Autowiring 服务 : How to use hwi/oauth-bundle in symfony 3. 4 + FOSUserBundle

sql - : operator for DQL queries

php - Symfony ArrayCollection 与 PersistentCollection