mirror of
https://github.com/doctrine/orm.git
synced 2026-03-23 22:42:18 +01:00
Entity Manager return repository with old entity manager after entity manager reset #5972
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @DangerLifter on GitHub (May 26, 2018).
Originally assigned to: @Majkl578 on GitHub.
Initially posted here: https://github.com/symfony/symfony/issues/26503
There are entities Product and Category with Many-to-One relation. In controller multiple products added in a loop. Each product is assigned to same category, which is loaded before loop. Product has unique field in database, so in loop "UniqueConstraintViolationException" is caught and loop going further with next product. Because exceptions causes entity manager to be closed there is code in cycle to reset manager if need it:
As category loaded once before loop it needs to be reloaded for new entity manager. If
$category = $em->getRepository(Category::class)->find($category->getId());is used it does not work and causesBut it correctly works with usage
$category = $em->find(Category::class, $category->getId());As I found it happens because $em->getRepository(Category::class) returns repository with old instance of entity manager.
@Majkl578 commented on GitHub (May 26, 2018):
Doctrine's EntityManager has no concept of resettability - once closed (i.e. by exception), it can no longer be used at all, neither can be used i.e. UnitOfWork. Any entity managed by the closed EntityManager becomes invalid (unmanaged) too.
Hence this looks like a wrong assumption in your code (i.e. expecting entity to outlive closed Entity Manager).
Hint: you can use
EntityManager::getReference()to get a managed placeholder of your object, but since it does not query the DB to check for its existence, you must ensure it's valid (i.e. not deleted in meantime).Closing as invalid for the reason above.