Skip to content

Instantly share code, notes, and snippets.

@sentenza
Last active June 28, 2020 14:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sentenza/739205fb70511372e260cef943df7530 to your computer and use it in GitHub Desktop.
Save sentenza/739205fb70511372e260cef943df7530 to your computer and use it in GitHub Desktop.
How to deal with Symfony and doctrine merge

You should use merge operation on entities which are in detached state and you want to put them to managed state.

Merging should be done like this $entity = $em->merge($detachedEntity). After that $entity refers to the fully managed copy returned by the merge operation. Therefore if your $form contains detached entities, you should adjust your code like this:

$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $detachedEntity) {
    $entity = $doctrineManager->merge($detachedEntity);  
    $doctrineManager->remove($entity);
}
$doctrineManager->flush();

However, in case that the $form does not contain detached entities, you should remove the merge operation, like this:

$doctrineManager = $this->getDoctrine()->getManager();
foreach ($form->getData()->getEntities() as $entity) {
    $doctrineManager->remove($entity);
}
$doctrineManager->flush();

This image should help you to understand entity state transitions. It is taken from Java Persistence API, but in Doctrine2 it is about the same.

JPA state transitions

Source: StackOverflow Reference: https://openjpa.apache.org/builds/1.2.3/apache-openjpa/docs/jpa_overview_em_lifecycle.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment