我们有一个包含多个表的主数据库。根据当前使用的客户端,我们将拥有未知数量的“重复”数据库。
设置如下
教义.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 保留一个新条目时,无论传递什么值,它都只使用它在 doctrine.yaml 中遇到的第一个实体管理器和连接。除非我传递一个不是 EntityManager 名称的字符串,否则我会收到 500 错误。
使用 ->getManager() 的任何变体也会导致 500 错误。我是 symfony 的新手
谢谢你
最佳答案
我以这种方式使用两个不同的管理器(在具有依赖注入(inject)的服务中):
在这个例子中,我将存储库直接注入(inject)到服务构造函数中。
<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>
关于php - 使用多个数据库连接访问存储库和实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55904667/