How to get different DBAL Connection in Symfony2 Doctrine2

血红的双手。 提交于 2020-02-24 14:48:03

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11945213/how-to-get-different-dbal-connection-in-symfony2-doctrine2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!