2

I have an entity "Entity1", that have an OneToOne (one-direction) relation with another entity "Entity2". Entity2 is managed by a different EntityManager.

Here is part of the Entity1:

/**
 * @ORM\OneToOne(targetEntity="Entity2")
 * @ORM\JoinColumn(name="Entity2ID", referencedColumnName="ID")
 **/
protected $entity2;

Entity2 already exists, Entity1 is a new entity. Here is part of the persisting logic:

$obj1 = new Entity1();
$obj1->setEntity2($this->entity2Manager
                        ->getRepository('VendorBunlde:Entity2')
                        ->find($entity2Id));
$this->entity1Manager->persist($obj1);
$this->entity1Manager->flush();

I got this error:

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

How can I force Doctrine to skip persisting Entity2 and in the same time keep the relation? I tried "->merge($obj1)" it works but I get null when I call $obj1->getId()?!

Mark Shehata
  • 151
  • 1
  • 12

2 Answers2

0

I would try the detach method:

An entity is detached from an EntityManager and thus no longer managed by invoking the EntityManager#detach($entity) method on it or by cascading the detach operation to it. Changes made to the detached entity, if any (including removal of the entity), will not be synchronized to the database after the entity has been detached.

$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't tried though, please let me know if it works, thanks.

acontell
  • 6,792
  • 1
  • 19
  • 32
0

This solution works for me: Using Relationships with Multiple Entity Managers

  • I removed the relationship between entity1 & entity2.
  • Added @PostLoad to load entity2.
Community
  • 1
  • 1
Mark Shehata
  • 151
  • 1
  • 12