Wasiim Maxamed
Wasiim Maxamed

Reputation: 1

how to connect to another database in symfony other than the configured one

I want to connect to another database and/or create a new one in symfony. How can I do that and at the same time get access to the tables of it?

I looked for how to do this inside the app

php bin/console doctrine:query:sql 'SELECT * FROM product'

but couldn't find any answer.

Upvotes: 0

Views: 3045

Answers (3)

You need to configure multiple entity managers, check How to Work with multiple Entity Managers and Connections.

Then you can use doctrine commands as below:

php bin/console doctrine:database:create --connection=<your_entity_manager_name>
php bin/console doctrine:query:sql --connection=<your_entity_manager_name>

Upvotes: 0

yTko
yTko

Reputation: 175

Look at this, should help: https://symfony.com/doc/current/doctrine/multiple_entity_managers.html

I short, you can define different entity managers that deals with different database connections

Upvotes: 0

AngelsDustz
AngelsDustz

Reputation: 64

You can't create a database directly from Symfony, but you can use Migrations to create tables. If you want to you can even generate the Migrations using the bin/console and doctrine:migrations:diff to generate migrations based off your Entities.

For the multiple databases you can use Service Containers to configure the Doctrine ORM then in your code you can grab the specific container and instantiate doctrine from there.

Also if you are interested in doing selects I would take a look at DQL as this allows solutions as follows:

// This assumes an entity called 'entity' exists.
$query = $entityManager->createQueryBuilder('entity');
return $query->getResult();

Upvotes: 1

Related Questions