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?
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.
You must execute command: $entityManager->detach($userEntity);
. The changes then will not reflected in the database after you call flush. Others entities will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With