Skip to content

Instantly share code, notes, and snippets.

@terox
Created October 14, 2014 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terox/9cce39ec87306f424743 to your computer and use it in GitHub Desktop.
Save terox/9cce39ec87306f424743 to your computer and use it in GitHub Desktop.
<?php
/**
* We want "clone/duplicate" -EntityM- keeping fk1 objec and cloning fk2. We are setting fk2 id
* to null ($fk2->setId(null)) to force EntityManger to persist new entity. But didn't work.
* Also doing $fk2 = new EntityB(). We are trying to do it in __clone method following the
* recomendations in Doctrine documentation, and the EntityManager throws something like that:
*
* "Doctrine\ORM\ORMException : Entity of type EntityM has identity through a foreign entity EntityB,
* 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 EntityM'.
* 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 operation".
*
* If we call EntityManager inside __clone (bad practise) doing a
* $em->persist($fk2)
* $em->flush()
*
* All works fine. But it is not a solution.
*
*
* After researching a bit, and specilly your comments, we are reconsiderating
* create a service that handle all logic to "clone or duplicate" from stractch:
* creating and setting values.
*
* Comments are appreciated. Thank you.
*/
class EntityM
{
/**
* ORM\Id
* @ORM\ManyToOne(targetEntity="EntityA", cascade={"persist"})
*/
protected $fk1;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="EntityB", cascade={"persist"})
*/
protected $fk2;
/**
* @ORM\Column(name="property1", type="string")
*/
protected $property;
// More properties
// ...
// Getters and setters
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment