Search code examples
symfonydoctrine-ormdoctrinesymfony4entitymanager

how to use two entity manager for one direction in symfony 4


I'm working with multiple Entity Managers, followed Symfony doc from here, but I want to use two entity manager for one dir. It's not working properly in findAll or findOneBy query, it's showing the result for 'default' entity manager.

in config/packages/doctrine.yaml :

dbal:
    # configure these for your database server
    default_connection: default
    connections:
        default:
            driver: 'pdo_mysql'
            server_version: '5.7'
            charset: utf8mb4
            default_table_options:
                charset: utf8mb4
                collate: utf8mb4_unicode_ci

            url: '%env(DATABASE_URL)%'

        blog:
            driver: 'pdo_mysql'
            server_version: '5.7'
            url: '%env(DATABASE_BLOG_URL)%'
            charset: utf8mb4
orm:
    auto_generate_proxy_classes: true
    default_entity_manager: default
    entity_managers:
        default:
            connection: default
            naming_strategy: doctrine.orm.naming_strategy.underscore
            mappings:
                Main:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: Main

        blog:
            connection: blog
            naming_strategy: doctrine.orm.naming_strategy.underscore
            mappings:
                blog:
                    is_bundle: false
                    type: annotation
                    dir: '%kernel.project_dir%/src/Entity'
                    prefix: 'App\Entity'
                    alias: blog

in controller:

    $entityManager = $this->getDoctrine()->getManager('blog');

    $University = $entityManager->getRepository(University::class)
            ->findOneBy(array('Code' => $Code));

Solution

  • i would recommend inject the connection as a service in your Controller and leverage autowiring

    //CONTROLLER

    public function testController(YourService $service){
            return $service->test();
    }
    

    //services.yml

    App\Service\YourService:
        public: true
        arguments: ['@doctrine.orm.entity_manager','@doctrine.orm.blog']
    

    //src/service/YourService.php

    class YourService {
        private $blog,$em;
    
    public function __construct(EntityManager $em, EntityManager $blog) {
        $this->em = $em
        $this->blog = $blog;
    }
    
     public function test()
        {
            //connect to blog
            $this->blog->getRepository(your_entity::class)->findAll();
            //connect to default
            $this->em->getRepository(your_entity::class)->findAll();
        }