How to use Symfony autowiring with multiple entity managers

后端 未结 3 871
旧时难觅i
旧时难觅i 2021-01-21 14:00

I would like to use the autowiring in a service that use 2 different entity manager. How to achieve something like that ?

use Doctrine\\ORM\\EntityManager;
class         


        
3条回答
  •  孤城傲影
    2021-01-21 14:41

    The easy way would be to autowire ManagerRegistry in your constructor and use it to get the managers you want by using the names of the entity manger you have set in your configuration file (doctrine.yaml) :

    use Doctrine\Common\Persistence\ManagerRegistry;
    class TestService
    {
    
        private $emA;
        private $emB;
        public function __construct(ManagerRegistry $doctrine)
        {
             $this->emA = $doctrine->getManager('emA');
             $this->emB = $doctrine->getManager('emB');
        }
    }
    

    And you should be able to use them as you want.


    Another way would be to follow this answer by Ron Mikluscak

提交回复
热议问题