问题
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
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:
you can inject the second entity manager to your repository class and then use createQueryBuilder to define your query.
service or Controller:
$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;
}
来源:https://stackoverflow.com/questions/59491565/use-two-entitymanagers-does-not-work-with-repository