使用多个数据库连接访问存储库和实体

时间:2019-04-29 13:42:09

标签: php mysql symfony

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

此设置类似于以下内容

doctrine.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

工作得很好。

但是我无法切换到特定的EntityManager来操纵正确的数据库。它始终使用默认值。

我知道很多问题都没有涉及到,但没有给出真正的答案

每个数据库都使用所有相同的实体和存储库。我要更改的只是symfony 4使用的数据库。

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

当我通过$ rep保留新条目时,无论传递什么值,它都只会使用第一个实体管理器,并且它会在doctrine.yaml中遇到。除非我传递的字符串不是EntityManager名称,否则会出现500错误。

使用-> getManager()的任何变体也会导致500错误。对symfony来说还很新

谢谢你

1 个答案:

答案 0 :(得分:0)

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

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

<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>
相关问题