简体   繁体   中英

Dynamic database selection using Symfony2 and Doctrine2

I am having the following problem: I have one core database containing Doctrine Entities that keep my login information to other databases. Every client that registers to my application will get his own database. I use subdomains to determain which database must be used. The client database contain other Doctrine Entities, in order to keep the client's data.

To determine the database based on the subdomain, I checked Symfony 2 : multiple and dynamic database connection and http://knpuniversity.com/screencast/question-answer-day/symfony2-dynamic-subdomains . I have tried the asker's solution and the answer's solution. The given solution works, but only for a part. I created a service to be able to switch between databases in the Controller, but when I create a new Entity, Symfony always wants to execute the CREATE TABLE on the main database.

I'd like Doctrine to divide the tables over the databases. I've also tried Annotations, but I couldn't get it to work. Does anyone have a suggestion on how to separate entities and put them in different databases? Ideally, I should be able to define the database to be used per Entity.

Additional info:

Symfony 2.3

Doctrine 2

If you have dynamic database, probably connected into second entity manager (for ex dynamic):

doctrine:
  dbal:
    connections:
      default:
        # default configuration
      dynamic:
        # placeholder used to replace connection information
  orm:
    entity_managers:
      default:
        connection: default
      dynamic:
        connection: dynamic
        mappings:
          MyBundle:
            type: annotation
            dir: DynamicEntity # for ext \My\MyBundle\DynamicEntity\Item class

Next saving:

$em = $this->get('doctrine')->getManager('dynamic');
$em->persist(new \My\MyBundle\DynamicEntity\Item());
$em->flush();

You have to rememeber about eneity manager mapping configuration ( more in symfony 2 documentation ). Without this you will be able to put each entity into both databases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM