当使用“自动”时,明确地设置Id与原则战略 [英] Explicitly set Id with Doctrine when using "AUTO" strategy

查看:55
本文介绍了当使用“自动”时,明确地设置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(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

旧解决方案

因为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(\Doctrine\ORM\Mapping\ClassMetadata::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 \Doctrine\ORM\Id\AssignedGenerator()); / code>

$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

祝福,

这篇关于当使用“自动”时,明确地设置Id与原则战略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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