0

Get Doctrine2 DBAL connection for different databases in Symfony2

Posted October 26th, 2013 in Razno and tagged , , , by Metod

Let’s say you have multiple databases you want to connect to and your config looks similar to the following:

So we have a default DBAL connection to db1 and we have 2 other databases db2 and db3 we want to connect to and perform some queries on.

How do we get the DBAL connections to them?

The Cookbook only tells us how to get the default (db1) connection:

$conDb1 = $this->get('database_connection');

If we want the connection to other 2, it goes like this:

$conDb2 = $this->get('doctrine.dbal.db2_connection');
$conDb3 = $this->get('doctrine.dbal.db3_connection');

The key part is of course: doctrine.dbal.%s_connection, where %s is replaced by the connection name you want to get.