Doctrine2 Entites - Is it possible to compare a "dirty" object with one of the database?

Is it possible to compare the state of an entity object between the current "dirty" version (an object for which some of its properties have been changed have not yet been saved) and the "original" version (data still in the database).

My assumption was that I could have a “dirty” object, then pull out a new one from the database and compare the two. For instance:

$entity = $em->getRepository('MyContentBundle:DynamicContent')->find($id); $editForm = $this->createContentForm($entity); $editForm->bind($request); if ($editForm->isValid()) { $db_entity = $em->getRepository('MyContentBundle:DynamicContent')->find($id); // compare $entity to $db_entity $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('content_edit', array('id' => $id))); } 

But, in my experience, $ entity and $ db_entity are always the same object (and have the same data as $ entity, after the $ request bind form). Is there a way to get a new version of $ entity along with a dirty version for comparison? The solutions I saw all pulled out the right data before the form was bound, but I would rather not have this limitation.

Update: To clarify, I am looking for not only changes in the properties of objects, but also collections of objects associated with them.

+6
source share
2 answers

After you clear $em , it will happen (it's done) in the database .. so ... you can get $db_entity before flush()


  • I'm not sure what you want .. but you can also use merge instead of persist .

    • merge returns object changed - identifier generated and configured
    • persist modifies your instance
  • If you want the object to be changed, not persisted , use it before flush .

  • EntityManager gives you the same instance because you are not $em->clear()
    • flush makes all changes (all dirty objects)
    • clear clears the memory cache. so when you find(..., $id) you will get a new instance
  • Is clone keyword for you? as in this example:

 $entity = $em->find('My\Entity', $id); $clonedEntity = clone $entity; 

And you can also read this: Wakeup or Clone implementation

+5
source

You can get what has changed on the object through Doctine UnityOfWork. This is pretty simple: after you save the entity, Doctrine knows what needs to be updated in the database. You can get this information by following these steps:

 // Run these AFTER persist and BEFORE flush $uow = $em->getUnitOfWork(); $uow->computeChangeSets(); $changeset = $uow->getEntityChangeSet($entity); 
+9
source

All Articles