我在我的 symfony 包中的 Resources/config/doctrine 文件夹中使用 yml-syntax 创建了一个实体:
Sulu\Bundle\TranslateBundle\Entity\Translation:
type: entity
table: tr_translations
id:
code:
type: string
column: idCodes
associationKey: id
catalogue:
type: string
column: idCatalogues
associationKey: id
fields:
value:
type: text
manyToOne:
code:
targetEntity: Code
inversedBy: tr_codes
joinColumn:
name: idCodes
referencedColumnName: id
catalogue:
targetEntity: Catalogue
inversedBy: tr_catalogues
joinColumn:
name: idCatalogues
referencedColumnName: id
这部分工作正常。但是,当我创建一些对象(如下面的代码所示)时,我收到一条错误消息,提示我必须使用刷新方法才能获取外键的 ID。
这是我当前正在使用的代码片段:
// create a new package and catalogue for the import
$package = new Package();
$package->setName($this->getName());
$catalogue = new Catalogue();
$catalogue->setLocale($this->getLocale());
$catalogue->setPackage($package);
$this->em->persist($package);
$this->em->persist($catalogue);
// load the file, and create a new code/translation combination for every message
$fileCatalogue = $loader->load($this->getFile(), $this->getLocale());
foreach ($fileCatalogue->all()['messages'] as $key => $message) {
$code = new Code();
$code->setPackage($package);
$code->setCode($key);
$code->setBackend(true);
$code->setFrontend(true);
$translate = new Translation();
$translate->setCode($code);
$translate->setValue($message);
$translate->setCatalogue($catalogue);
$this->em->persist($code);
$this->em->flush(); //FIXME no flush in between, if possible
$this->em->persist($translate);
}
// save all the changes to the database
$this->em->flush();
如果我不在 foreach 循环中调用刷新,我会收到以下错误,我完全理解这个错误,但是对于这个问题没有更优雅的解决方案吗?
Doctrine\ORM\ORMException :类型的实体
Sulu\Bundle\TranslateBundle\Entity\Translation 通过
外部实体 Sulu\Bundle\TranslateBundle\Entity\Code,但是这个
实体本身没有身份。你必须打电话
EntityManager#persist() 在相关实体上并确保
标识符是在尝试持久化之前生成的
'Sulu\Bundle\TranslateBundle\Entity\Translation'。邮寄的情况下
插入ID生成(例如MySQL自动增量或PostgreSQL
SERIAL)这意味着您必须在两者之间调用 EntityManager#flush()
坚持经营。
不幸的是,根据教义文档 http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-objects.html#persisting-entities你必须调用flush来获取你的外键的ID:
生成的实体标识符/主键保证是
在下一次成功的刷新操作之后可用
有问题的实体。您不能依赖生成的标识符
调用 persist 后可直接使用。反之亦然。
您不能依赖生成的标识符在
刷新操作失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)