简体   繁体   English

教义坚持实体,相关实体以原实体为关键

[英]Doctrine persist entity with related entities having former entity as key

I have an entity which has a oneToMany relationship. 我有一个具有oneToMany关系的实体。 The related entity has identity through the id of the first entity + another field. 相关实体通过第一个实体的ID +另一个字段具有标识。 I tried to set cascade: ["persist"] on the first entity but when I'm trying to persist it it tells me that the related entities cannot be persisted and I first have to flush the first entity. 我尝试在第一个实体上设置级联:[“ persist”],但是当我尝试持久化它时,它告诉我相关实体无法持久化,因此我首先必须刷新第一个实体。 But if I simply remove the cascade and flush the first entity it will give an exception saying that it won't persist because the related entities aren't persisted and i should set persist to cascade. 但是,如果我只是删除级联并刷新第一个实体,它将给出一个异常说它不会持久,因为相关的实体不是持久性的,我应该将持久性设置为级联。

How to I solve this? 我该如何解决? The only solution that comes to mind is: 想到的唯一解决方案是:

$relatedEntities = $entity1->getRelatedEntities();
$entity1->setRelatedEntities(new ArrayCollection());
$em->persist($entity1);
$em->flush($entity1);

$entity1->setRelatedEntities($relatedEntities);
$em->flush();

Is there any other way to do this? 还有其他方法吗?

As the error says you have to flush your first entity first. 如错误所示,您必须先刷新第一个实体。 Then you flush the related entity. 然后,刷新相关实体。 Some pseudo code: 一些伪代码:

$entity_one = new Something();

//Now set object values

$em->persist($entity_one);
$em->flush();

$entity_two = new SomethingElse();

//Now set object values (set the related/relation to the first entity)

$em->persist($entity_two);
$em->flush()

I'm not entirely sure you need to set the first entity to the second entity once you have flushed it. 我不确定是否在刷新后将第一个实体设置为第二个实体。 But you can find out very easy by trying it out ;) 但是,您可以通过尝试轻松地找到它;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM