使用两个实体管理器不适用于存储库 [英] Use two entitymanagers does not work with repository
问题描述
我正在使用两个实体管理器来处理两个数据库.问题是我无法为我的存储库设置正确的实体管理器(它使用默认的实体管理器).当我将实体持久化到数据库时,它工作正常(使用 wp
entitymanager).如何使用 wp
实体管理器?
I'm using two Entitymanagers to work with two databases. The problem is that I can't set the correct entitymanager for my repository(it uses the default entitymanager). When I persist the entity to the database, it works fine (with the wp
entitymanager) .
How can I use the wp
entitymanager?
问题与此类似.解决方法没用
The problem is similar to this one. The solution didn't work
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
事件监听器
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());
...
推荐答案
您可以将第二个实体管理器注入您的存储库类,然后使用 createQueryBuilder 来定义您的查询.
you can inject the second entity manager to your repository class and then use createQueryBuilder to define your query.
服务或控制器:
$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;
}
这篇关于使用两个实体管理器不适用于存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!