I’m using Symfony 7.1.3 with Doctrine DBAL 4.1 and have configured multiple database connections in my doctrine.yaml
. My default connection (npreports
) works fine, but when I try to run queries on a second connection (npfactory
), I encounter the following error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'npreports.scheduled_tasks' doesn't exist
The error seems to indicate that it’s still trying to use the default connection (npreports
) even though the query is meant for npfactory
.
Here’s my database configuration in doctrine.yaml
:
doctrine:
dbal:
default_connection: npreports
connections:
npreports:
url: '%env(resolve:DATABASE_REPORTS_URL)%'
npfactory:
url: '%env(resolve:DATABASE_FACTORY_URL)%'
I inject the npfactory
connection in my repository and controller like this:
public function __construct(Connection $npfactory)
{
$this->npfactory = $npfactory;
}
Environment:
- Symfony: 7.1.3
- Doctrine DBAL: 4.1.0
- Doctrine ORM: 3.2.2
What I’ve tried:
- I can successfully query
npreports
without any issues. - Changing the default connection to
npfactory
works, but this is not ideal as I need both connections. - I’ve confirmed that the table
scheduled_tasks
exists in thenpfactory
database.
Is there something wrong with how Symfony is managing the database connections, or am I missing something with Doctrine’s configuration? How can I ensure that the correct connection is being used for each query?
2
Answers
I was able to resolve the issue by explicitly injecting the correct database connection using an alias in
services.yaml
. Here's how I did it:While this solves the problem, I'm not entirely happy with this approach. Having to explicitly define the connection in the service container feels cumbersome, especially for cases where flexibility with multiple connections should be more seamless.
I found a solution that meets my requirements for simplicity and flexibility without additional configuration in
services.yaml
. This approach is more maintainable and allows easy addition of new database connections. Here’s what I did:Improved Solution
doctrine.yaml
configuration:services.yaml
:With this approach, I achieved the following:
services.yaml
for each new repository class.doctrine.yaml
without requiring further changes to the configuration or repository classes.This solution required only minimal changes to my existing code while providing the desired flexibility and simplicity. I can continue to use my repository classes as I’m accustomed to, with the only difference being that I inject the
ConnectionResolver
instead of the directConnection
.