gpt4 book ai didi

php - 在学说中坚持具有两个外国身份的对象

转载 作者:可可西里 更新时间:2023-11-01 01:03:04 25 4
gpt4 key购买 nike

我在 Resources/config/doctrine 文件夹中使用 yml-syntax 在我的 symfony 包中创建了一个实体:

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

这部分工作正常。但是当我像下面的代码一样创建一些对象时,我收到一条错误消息,提示我必须使用 flush 方法才能获取外键的 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 循环中调用 flush,我会得到以下错误,我完全理解,但是对于这个问题没有更优雅的解决方案吗?

Doctrine\ORM\ORMException : Entity of type Sulu\Bundle\TranslateBundle\Entity\Translation has identity through a foreign entity Sulu\Bundle\TranslateBundle\Entity\Code, however this entity has no identity itself. You have to call EntityManager#persist() on the related entity and make sure that an identifier was generated before trying to persist 'Sulu\Bundle\TranslateBundle\Entity\Translation'. In case of Post Insert ID Generation (such as MySQL Auto-Increment or PostgreSQL SERIAL) this means you have to call EntityManager#flush() between both persist operations.

最佳答案

不幸的是,根据 Doctrine Docs你必须调用 flush 来获取外键的 ID:

Generated entity identifiers / primary keys are guaranteed to be available after the next successful flush operation that involves the entity in question. You can not rely on a generated identifier to be available directly after invoking persist. The inverse is also true. You can not rely on a generated identifier being not available after a failed flush operation.

关于php - 在学说中坚持具有两个外国身份的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18143630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com