在学说2中启用IDENTITY_INSERT

时间:2015-12-06 13:26:47

标签: php sql-server doctrine-orm sqlsrv

我拥有一个mssql数据库服务器,并使用doctrine2(sqlsrv)连接到它

我想创建具有给定id的新实体实例。但是,如果我尝试它,我会收到一个错误:

Cannot insert explicit value for identity column in table 'my_test_table' when IDENTITY_INSERT is set to OFF

我删除了@GeneratedValue注释。但我仍然得到这个错误。

之后,我在`SQL Server管理工作室中运行了这个脚本:

SET IDENTITY_INSERT my_test_table ON

不幸的是我仍然得到错误,我无法理解为什么

2 个答案:

答案 0 :(得分:0)

必须在学说的连接上调用

$em->getConnection()->prepare("SET IDENTITY_INSERT my_test_table ON")->execute();

答案 1 :(得分:0)

我的设置可能有所不同,或者Doctrine中的某些内容可能已经发生了变化,但对于Doctrine ORM 2.5.6,PHP 7.0.17和SQL Server 2014,这对我来说不起作用。

尽管在我的同花顺之前设定它,但它不会起作用。它也不能用于类层次结构中的多个表,因为IDENTITY_INSERT一次只能打开一个表。

我能够通过使用连接的包装类来弄清楚如何做到这一点。 Doctrine使用wrapperClass配置参数支持此操作。以下是我的代码。

<?php
declare(strict_types=1);

namespace Application\Db;

/**
 * Class SqlSrvIdentityInsertConnection
 * This class is to enable Identity Insert when using Doctrine with SQLServer. 
 * Must use this class with the "wrapperClass" configuration option 
 * for EntityManager::create
 */
class SqlSrvIdentityInsertConnection extends \Doctrine\DBAL\Connection
{
    private $tables = [];
    private $enabled = [];

    public function enableIdentityInsertFor(string $tableName)
    {
        $this->tables[] = $tableName;
        $this->enabled[$tableName] = false;
    }

    private function setIdentityInsert(string $statement) {
        // Must turn off IDENTITY_INSERT if it was enabled, and this table
        // isn't in the query. Must do this first!
        foreach($this->tables as $tableName) {
            if (stristr($statement, "INSERT INTO $tableName") === false) {
                if ($this->enabled[$tableName]) {
                    parent::exec("SET IDENTITY_INSERT " . $tableName . " OFF");
                    $this->enabled[$tableName] = false;
                }
            }
        }

        foreach($this->tables as $tableName) {
            if (stristr($statement, "INSERT INTO $tableName") !== false) {
                parent::exec("SET IDENTITY_INSERT ".$tableName." ON");
                $this->enabled[$tableName] = true;

                // Only one can be enabled at a time
                return;
            }
        }
    }

    public function prepare($statement)
    {
        $this->setIdentityInsert($statement);
        return parent::prepare($statement);
    }
}

以下是使用

插入某些实体时的使用方法
    $em->persist($newEntity);

    /** @var SqlSrvIdentityInsertConnection $conn */
    $conn = $em->getConnection();

    $metadata = $this->session->getClassMetaData(MyEntityClass::class);
    $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
    $conn->enableIdentityInsertFor($metadata->getTableName());

    $em->flush();