使用“AUTO"时使用 Doctrine 显式设置 Id;战略 [英] Explicitly set Id with Doctrine when using "AUTO" strategy
问题描述
我的实体使用此注释作为其 ID:
My entity uses this annotation for it's ID:
/**
* @orm:Id
* @orm:Column(type="integer")
* @orm:GeneratedValue(strategy="AUTO")
*/
protected $id;
从一个干净的数据库中,我从旧数据库中导入现有记录并尝试保留相同的 ID.然后,在添加新记录时,我希望 MySQL 像往常一样自动增加 ID 列.
From a clean database, I'm importing in existing records from an older database and trying to keep the same IDs. Then, when adding new records, I want MySQL to auto-increment the ID column as usual.
不幸的是,Doctrine2 似乎完全忽略了指定的 ID.
Unfortunately, it appears Doctrine2 completely ignores the specified ID.
新解决方案
根据以下建议,以下是首选解决方案:
Per recommendations below, the following is the preferred solution:
$this->em->persist($entity);
$metadata = $this->em->getClassMetaData(get_class($entity));
$metadata->setIdGeneratorType(DoctrineORMMappingClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new DoctrineORMIdAssignedGenerator());
旧解决方案
由于 Doctrine 以 ClassMetaData 为中心来确定生成器策略,因此必须在 EntityManager 中管理实体后对其进行修改:
Because Doctrine pivots off of the ClassMetaData for determining the generator strategy, it has to be modified after managing the entity in the EntityManager:
$this->em->persist($entity);
$metadata = $this->em->getClassMetaData(get_class($entity));
$metadata->setIdGeneratorType(DoctrineORMMappingClassMetadata::GENERATOR_TYPE_NONE);
$this->em->flush();
我刚刚在 MySQL 上测试了它,它按预期工作,这意味着具有自定义 ID 的实体使用该 ID 存储,而没有指定 ID 的实体使用 lastGeneratedId() + 1
.>
I just tested this on MySQL and it worked as expected, meaning Entities with a custom ID were stored with that ID, while those without an ID specified used the lastGeneratedId() + 1
.
推荐答案
尽管您的解决方案适用于 MySQL,但我未能使其适用于 PostgreSQL,因为它是基于序列的.
Although your solution work fine with MySQL, I failed to make it work with PostgreSQL as It's sequence based.
我必须添加这一行以使其完美运行:
I've to add this line to make it work perfectly :
$metadata->setIdGenerator(new DoctrineORMIdAssignedGenerator());
这篇关于使用“AUTO"时使用 Doctrine 显式设置 Id;战略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!