如何在Symfony2中使用Doctrine2创建2个连接(mysql和postgresql)

Nek*_*eka 4 symfony doctrine-orm

我是Symfony2的新手.我的问题很简单.我会在不同的主机和驱动程序中使用2个连接到DB.

你能帮帮我吗?

小智 8

你可以这样做:

doctrine:
    dbal:
        default_connection: alpha
        connections:
            alpha:
                driver:     pdo_mysql
                host:       localhost
                dbname:     alpha
                user:       root
                charset:    UTF8
            beta:
                driver:     pdo_pgsql
                host:       localhost
                dbname:     beta
                user:       root
                charset:    UTF8
    orm:
        auto_generate_proxy_classes: %kernel.debug%
        entity_managers:
            alpha:
                connection: alpha
            beta:
                connection: beta
Run Code Online (Sandbox Code Playgroud)

您看,我们在该dbal部分中声明了两个连接,并在orm一个中声明了两个实体管理器.

之后,您可以同时使用:

$emAlpha = $this->getDoctrine()->getEntityManager('alpha');
$emBeta  = $this->getDoctrine()->getEntityManager('beta');
Run Code Online (Sandbox Code Playgroud)

当alpha一个被定义为默认值时,您可以在不指定其名称的情况下访问它:

$emAlpha = $this->getDoctrine()->getEntityManager();
Run Code Online (Sandbox Code Playgroud)