我拥有一个mssql数据库服务器,并使用doctrine2(sqlsrv)连接到它。
我想用给定的id创建新的实体实例。但如果我试一试,我会发现一个错误:
Cannot insert explicit value for identity column in table 'my_test_table' when IDENTITY_INSERT is set to OFF我已经删除了@GeneratedValue注释。但我还是会犯这个错误。
之后,我在“Server管理演播室”中运行了这个脚本:
SET IDENTITY_INSERT my_test_table ON不幸的是,我还是搞错了,我不明白为什么
发布于 2015-12-06 15:18:23
它必须以学说的联系为依据
$em->getConnection()->prepare("SET IDENTITY_INSERT my_test_table ON")->execute();发布于 2017-03-18 00:46:10
我的设置可能有些不同,或者Doctrine中的某些东西可能已经改变了,但是对于DoctrineORM2.5.6、PHP7.0.17和Server 2014来说,这是行不通的。
尽管在我的同花顺之前设置了它,它还是行不通的。它也不能适用于来自类层次结构的多个表,因为IDENTITY_INSERT一次只能打开一个表。
我能够通过为连接使用包装类来了解如何做到这一点。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();https://stackoverflow.com/questions/34117918
复制相似问题