我有一个实体" Entity1",它与另一个实体" Entity2"具有OneToOne(单向)关系。 Entity2由不同的EntityManager管理。
以下是Entity1的一部分:
/**
* @ORM\OneToOne(targetEntity="Entity2")
* @ORM\JoinColumn(name="Entity2ID", referencedColumnName="ID")
**/
protected $entity2;
Entity2已经存在,Entity1是一个新实体。这是持久逻辑的一部分:
$obj1 = new Entity1();
$obj1->setEntity2($this->entity2Manager
->getRepository('VendorBunlde:Entity2')
->find($entity2Id));
$this->entity1Manager->persist($obj1);
$this->entity1Manager->flush();
我收到了这个错误:
A new entity was found through the relationship 'MyBundle\\Entity\\Entity1#entity2' that was not configured to cascade persist operations for entity: VendorBundle\\Entity\\Entity2@0000000008fbb41600007f3bc3681401. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={\"persist\"}). If you cannot find out which entity causes the problem implement 'VendorBundle\\Entity\\Entity2#__toString()' to get a clue
如何强制Doctrine跳过持久化Entity2并同时保持关系?我试过" - >合并($ obj1)"它有效,但当我调用$ obj1-> getId()时,我得到null?!
答案 0 :(得分:0)
我会尝试detach方法:
实体与EntityManager分离,因此不再受管理 通过在其上或通过调用EntityManager#detach($ entity)方法 将分离操作级联到它。对分离的更改 实体,如果有的话(包括删除实体),将不会 分离实体后同步到数据库。
$obj1 = new Entity1();
$obj2 = $this->entity2Manager
->getRepository('VendorBunlde:Entity2')
->find($entity2Id);
$obj1->setEntity2($obj2);
$this->entity1Manager->detach($obj2);
$this->entity1Manager->persist($obj1);
$this->entity1Manager->flush();
但是,Haven试过,请告诉我它是否有效,谢谢。
答案 1 :(得分:0)
此解决方案适用于我:Using Relationships with Multiple Entity Managers