首页 > 解决方案 > 使用多个数据库连接访问存储库和实体

问题描述

我们有一个包含多个表的主数据库。根据当前使用的客户端,我们将拥有未知数量的“重复”数据库。

这是设置如下

教义.yaml

doctrine:
  dbal:
    default_connection: default
    connections:
      default:
        driver: pdo_mysql
        server_version: '5.7'
        charset: utf8mb4
        url: '%env(resolve:DATABASE_URL)%'
      School_A:
        driver: pdo_mysql
        server_version: '5.7'
        charset: utf8mb4
        url: 'mysql://nibbr:nibbr@127.0.0.1:3306/School_A'
      School_B:
        driver: pdo_mysql
        server_version: '5.7'
        charset: utf8mb4
        url: 'mysql://nibbr:nibbr@127.0.0.1:3306/School_B'
  orm:
    default_entity_manager: default
    entity_managers:
      default:
        connection: default
        naming_strategy: doctrine.orm.naming_strategy.underscore
        mappings:
          App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
            alias: App
      4bf40159870dc1b23c97e7906a303f39:
        connection: School_A
        naming_strategy: doctrine.orm.naming_strategy.underscore
        mappings:
          App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
      46f0618dadff645591073709906f006c:
        connection: School_B
        naming_strategy: doctrine.orm.naming_strategy.underscore
        mappings:
          App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src'
            prefix: 'App'

现在数据库存在,

迁移使用

 php bin/console doctrine:migrations:migrate --em=46f0618dadff645591073709906f006c

工作得很好。

但我无法切换到特定的 EntityManagers 来操作正确的数据库。它总是使用默认值。

我知道这已经被触及了很多,但没有给出真正的答案

每个数据库使用所有相同的实体和存储库。我只想改变 symfony 4 使用的数据库。

 $rep = $this->getDoctrine()->getRepository(SchoolStudent::class,'46f0618dadff645591073709906f006c');

当我通过 $rep 持久化一个新条目时,无论传递什么值,它都只使用第一个实体管理器和它在教义.yaml 中遇到的连接。除非我传递一个不是 EntityManager 名称的字符串,否则我会收到 500 错误。

使用 ->getManager() 的任何变体也会导致 500 错误。我对 symfony 很陌生

非常感谢你

标签: phpmysqlsymfony

解决方案


我以这种方式使用两个不同的管理器(在具有依赖注入的服务中):

在此示例中,我将存储库直接注入到服务构造函数中。

<service id="my_service_id" class="FQCN">
    <argument type="service">
        <service class="Doctrine\ORM\DocumentRepository">
            <factory service="doctrine.orm.46f0618dadff645591073709906f006c_entity_manager" method="getRepository"/>
            <argument>Namespace\SchoolStudent</argument>
        </service>
    </argument>
</service>

推荐阅读