使用两个实体管理器不适用于存储库

时间:2019-12-26 17:30:42

标签: symfony4

我正在使用两个Entitymanager来处理两个数据库。问题是我无法为我的存储库设置正确的entitymanager(它使用默认的entitymanager)。当我将实体持久保存到数据库时,它可以正常工作(使用wp实体管理器)。 如何使用wp实体管理器?

问题与此类似。该解决方案无效

Use different Entity Manager in the Repository of specific Entity objects

doctrine.yaml

    orm:
        default_entity_manager: default
        auto_generate_proxy_classes: true
        entity_managers:
            default:
                connection: default
                naming_strategy: doctrine.orm.naming_strategy.underscore
                auto_mapping: true
                mappings:
                    App:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/Entity'
                        prefix: 'App\Entity'
                        alias: App
            wp:
                naming_strategy: doctrine.orm.naming_strategy.underscore
                connection: wp
                mappings:
                    Appwp:
                        is_bundle: false
                        type: annotation
                        dir: '%kernel.project_dir%/src/Entitywp'
                        prefix: 'App\Entitywp'
                        alias: Appwp

EventListener

class CustomSessionListener
{
    function __construct(Security $security,ManagerRegistry $em,WpSessionTableRepository $sessionTableRepository) {

        $this->security = $security;
        $this->em = $em;
        $this->sessionTableRepository = $sessionTableRepository;
    }


    public function onKernelController(ControllerEvent $event)
    {
        $user = $this->security->getUser();
        $manager=$this->em->getManager("wp");
        $repository=$manager->getRepository(WpSessionTable::class,"wp");

            if(!is_null($user)){//TODO){
                $sessionTableObj=new WpSessionTable();
                $sessionTableObj=$repository->findByEmail($user->getEmail());



...

1 个答案:

答案 0 :(得分:1)

您可以将第二个实体管理器注入到存储库类中,然后使用createQueryBuilder定义查询。

服务或控制器:

$entityManager = $this->getDoctrine()->getManager('wp');
$WpSessionTable = $entityManager->getRepository(WpSessionTable::class)
            ->findObjectById($entityManager,$id);

WpSessionTableRepository:

public function findObjectById(EntityManager $em,$id){

    $WpSessionTable = $em->createQueryBuilder()
        ->select('w')
        ->from(WpSessionTable::class,'w')
        ->where('w.id = :id')
        ->setParameter('id',$id)
        ->getQuery()

    return $WpSessionTable;
}