使用“AUTO"时使用 Doctrine 显式设置 Id战略 [英] Explicitly set Id with Doctrine when using "AUTO" strategy

查看:17
本文介绍了使用“AUTO"时使用 Doctrine 显式设置 Id战略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体使用这个注解作为它的 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.p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆