Today I setup Symfony 4 with two entity managers (two different MsSQL databases) and was having issues with my custom repository functions for entities on my second entity manager querying the default entity manager instead of it's own. I even tried setting the correct entity manager before doing the
$em->getRepository() call and it was still hitting the wrong database.
This was really strange because the functions outside my custom repository (such as
$em->findOneBy) were working correctly and returning results. This only started happening when I started writing custom repository functions.
Debugging the problem
Since this only happens when using custom repository functions I decided to look into that first, more specifically the
Looks like it is calling the
__construct method on the
parent which is
ServiceEntityRepository so lets jump to that and see what is going on:
When I dump the
$manager variable and run the page we will see that it is actually returning the wrong entity manager here. This seems to be the culprit. Now we got to think what would cause this to happen. This is where I turn to the
doctrine.yaml config file to see if there is any issues I can see.
The only thing that I could see that could cause problems would be the
default entity manager is using the path
App\Entity but the second entity manager is using
App\Entity\ProductStore so it must be accidentally thinking
ProductStore entities are under the
App\Entity namespace instead (basically detecting wrong namespace for the second EM). I decided to search and see if anyone else had this issue and sure enough this guy did. Looks like the fix is pretty easy..
Move your entities under
App\Entity to their own folder such as
App\Entity\Main and the namespaces will be correctly detected. Doing this solved the problem and I no longer have any issues. I tried changing the order of the items in my
doctrine.yaml file but that only fixed it in a couple of situations and I still had some issues with it.
I wanted to document this just-in-case someone else runs into the same problem.