Symfony is configured to work with the main database, but in one place you need to connect to another database, pick up the information and close the connection. How to do it from the controller?
1 answer
It is necessary to add an additional connection in the settings:
doctrine: dbal: default_connection: default connections: default: driver: pdo_mysql host: '%database_host%' port: '%database_port%' dbname: '%database_name%' user: '%database_user%' password: '%database_password%' charset: UTF8 customer: driver: pdo_mysql host: '%database_host2%' port: '%database_port2%' dbname: '%database_name2%' user: '%database_user2%' password: '%database_password2%' charset: UTF8 orm: default_entity_manager: default entity_managers: default: connection: default mappings: AppBundle: ~ AcmeStoreBundle: ~ customer: connection: customer mappings: AcmeCustomerBundle: ~ In the controller:
class UserController extends Controller { public function indexAction() { // All three return the "default" entity manager $em = $this->get('doctrine')->getManager(); $em = $this->get('doctrine')->getManager('default'); $em = $this->get('doctrine.orm.default_entity_manager'); // Both of these return the "customer" entity manager $customerEm = $this->get('doctrine')->getManager('customer'); $customerEm = $this->get('doctrine.orm.customer_entity_manager'); } } Requests can be written native if there are no сущностей in the second base.
/** @var EntityManager $em */ $em = $this->getDoctrine()->getManager(); $conn = $em->getConnection(); $users = $conn->fetchAll('SELECT * FROM users'); Documentation links: http://symfony.com/doc/current/doctrine/multiple_entity_managers.html
- in the mappings settings for what? It is necessary to indicate in it which bandlets which manager is used? - thecoder
|