首页 > 解决方案 > 在 Symfony 5 中从多个数据库恢复数据的问题

问题描述

我按照 Symfony 的建议为两个数据库创建了两个连接: https ://symfony.com/doc/current/doctrine/multiple_entity_managers.html

我使用 Symfony 5.0。

我配置了两个实体管理器:

# config/packages/doctrine.yaml
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                url: '%env(resolve:DATABASE_URL)%'     #bdd-main
            erp:
                url: '%env(DATABASE_ERP_URL)%'         #bdd-erp

    orm:
        auto_generate_proxy_classes: true
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
                mappings:
                    Main:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: Main
            erp:
                connection: erp
                naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
                mappings:
                    Erp:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/EntityErp'
                        prefix: 'App\EntityErp'
                        alias: Erp

对于测试,我在 EntityErp 中创建了一个 Toto 对象(因此对于数据库“bdd-erp”)。

当我尝试保存对象时,我可以做到:

    $erpEntityManager = $this->getDoctrine()->getManager('erp');
    $toto = new Toto();
    $toto->setName('Toto');
    $erpEntityManager->persist($toto);
    $erpEntityManager->flush();

在数据库“bdd-erp”中,该对象存在。

但是,当我只想恢复所有对象时,它不起作用:

$totos = $this->getDoctrine()
        ->getRepository(Toto::class, 'erp')
        ->findAll();

它试图连接到错误的数据库,所以我有这个错误:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2 FROM Toto t0':

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'bdd-erp.toto' doesn't exist

编辑:我试过这个,但仍然是同样的问题:

$emErp = $this->getDoctrine()->getManager('erp');  
$totos = $emErp->getRepository(Toto::class)->findAll();

我不明白,我做错了什么?

==> 编辑 - 解决方案: 我找到了解决方案。最后,这是 Symfony 5 的异常。我重命名了实体文件夹“ErpEntity”(而不是“EntityErp”)并且它可以工作(我在 'App\Entity\Erp' 之前尝试过,但仍然是错误)。奇怪,但我可以关闭这个帖子。

标签: phpmysqlsymfonydoctrinemulti-database

解决方案


我找到了解决方案。最后,这是 Symfony 5 的异常。我将实体文件夹重命名为“ErpEntity”(而不是“EntityErp”)并且它可以工作。奇怪,但我可以关闭这个帖子。


推荐阅读