Search code examples
repositoryentityentitymanagersymfony4

Symfony 4 one entity, two entity Manager


Hello everyone, I'm trying to have 2 entityManagers for one entity in Symfony4 but I have some trouble to do this.

When I persist an entity it works,(For example if have two entity Mananagers : Customer and Default ,when I use Customer or Default to persist) but when I want to use Repository, The first entity Managare in doctrine.yaml is always used. I have to do this because I have 2 databases. One in internet and one inside my intranet that i have created and I search to do is that when the user click one button for example. It update the database on internet.

config/packages/doctrine.yaml

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver: pdo_mysql
                host: **************
                port: 3306
                dbname: intranetDb
                user: **********
                password: *****
                charset: UTF8

            customer:
                driver: pdo_mysql
                host: internetDb
                port: 3306
                dbname: *********
                user:   *********
                password: *********
                charset: UTF8




    orm:
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                auto_mapping: false
                mappings:
                    Main:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: Main
            customer:
                connection: customer
                auto_mapping: false
                mappings:
                    Customer:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: Main

MyController.php

..
$drug = $this->getDoctrine()->getRepository(Drug::class,'customer')->findAll() ; 
..

This code always give me the data inside of default and if I put customer first inside of orm the customer is always given.

Some help will be welcome because I have this problem in few days and I have no Idea to solve this(It's probably because of symfony version that I didn't found solution inside forum).

Thank you.(And sorry for my bad English)


Solution

  • You can get the repository from an entity manager, instead of getting it from the ManagerRegistry returned by getDoctrine().

    Example:

    [...]
    
    $this->getDoctrine()->getManager('manager_name')->getRepository('class_name');
    
    [...]