Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I discard non-flushed changes to an entity in Doctrine 2?

I used SQL-queries-based database access level for a long time. But now I decided to use ORM Doctrine2. At this moment I have one conceptual misunderstanding of entities workflow.

Best described by example:

 try {
   $user = $entityManager->find('User', 1);
   $user->setName('New name');
   $entityManager->flush();
 }
 catch (...)
 {
   // !we are here: changes failed and $user-row in DB was not updated
 }

 // ...

 $user = $entityManager->find('User', 1);
 $user->setOther('Other');
 $entityManager->flush(); // <- in this request both [other] and [name] fields will be updated to DB, but only [other] update expected

In first code block I fetched $user object. Changed [name] and tried to save it, but failed. In the second block (unrelated to the first) I fetched $user object again. But ORM returned link to the same object as the first time. So this object has already changed [name] property. In the last line of second block I wanted to save just [other] filed, but both [other] and [name] will be updated.

What is the right way to resolve this situation?

like image 585
Valera Leontyev Avatar asked May 25 '12 08:05

Valera Leontyev


2 Answers

This is by design.

The entity manager ensures that you always get the same entity back for a given id. After all, that's what identity means. There can only be a single, unique, user with id 1.

If you want to "refresh" an entity from the database, EntityManager::refresh() will do that for you. From the docs:

Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.

like image 105
timdev Avatar answered Oct 21 '22 01:10

timdev


You must execute command: $entityManager->detach($userEntity); . The changes then will not reflected in the database after you call flush. Others entities will work.

like image 45
Pipaslot Avatar answered Oct 21 '22 01:10

Pipaslot