Say I load a user by id:
$user = $em->find('Domain\Model\User', 123);
And now run a DQL query to select several users, among them this already known user:
$users = $em->createQuery('SELECT u FROM Domain\Model\User u')->getResult();
If user 123 has changed in the database between these two queries (supposing I'm not inside a REPEATABLE READ
transaction), will this query refresh user 123 with the fresh data returned by the query, or will it just return the object from the identity map while ignoring the new data?
After testing this exact use case, it turns out that Doctrine 2 does not refresh an existing entity with the data returned by a DQL query, and only returns it as is from the identity map.
I finally found the relevant documentation confirming this:
In normal operation a result-set that loads data of an already existing entity is discarded in favor of the already existing entity.
It also gives a way to force the DQL query to refresh the entity, using Query::HINT_REFRESH
:
If you specify this hint and a query returns the data for an entity that is already managed by the UnitOfWork, the fields of the existing entity will be refreshed.
Which is quite handy and easy to use:
use Doctrine\ORM\Query;
$users = $em->createQuery('SELECT u FROM Domain\Model\User u')
->setHint(Query::HINT_REFRESH, true)
->getResult();
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