Mirage
Mirage

Reputation: 31548

How to get different DBAL Connection in Symfony2 Doctrine2

I have two connection in my config.yml file

doctrine:
      dbal:
         default:
         connection2

Then in my class , i use this

$em = $this->container->get('doctrine')->getEntityManager();

But it is getting the default connection. How can i use the second Connection

Is it possible that i can use it from service.

Upvotes: 2

Views: 1617

Answers (1)

Timo Haberkern
Timo Haberkern

Reputation: 4439

You have to define both a DBAL connection and an entity manager in the config.yml

doctrine:
    dbal:
        default_connection:   connection1
        connections:
            connection1:
                ...
            connection2:
                ...
    orm:
        default_entity_manager: em1
        entity_managers:
            em1:
                 connection: connection1
                 ....
            em2:
                 connection: connection2

No you can access the Entity mangager with:

$em = $this->container->get('doctrine')->getEntityManager();
// Returns $em1/connection1

$em = $this->container->get('doctrine')->getEntityManager('em1');
// Returns $em1/connection1

$em = $this->container->get('doctrine')->getEntityManager('em2');
// Returns $em2/connection2

Upvotes: 3

Related Questions