Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

php - Doctrine 2 - Multiple databases configuration and use

I have a Symfony2 project with a MySQL db:

#app/config/config.yml
doctrine:
    dbal:
        driver:   %database_driver%    # <
        host:     %database_host%      # |
        port:     %database_port%      # | Defined in
        dbname:   %database_name%      # | parameters.ini
        user:     %database_user%      # |
        password: %database_password%  # <

    orm:
        auto_generate_proxy_classes: %kernel.debug%
        auto_mapping: true

Now I'd like to make simple queries (like routine calls) to an other database.

Should I define an other dbal into the config file ?
If yes, how can it be configured while keeping the default connection for the project ?
Do I have to configure an orm for each connection ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add another level of configuration and also use multiple entity managers as Doctrine uses 1 entity manager per database connection .. your configuration might look something like this :

doctrine:
    dbal:
      connections:
        default:
          driver:   %database_driver%    # <
          host:     %database_host%      # |
          port:     %database_port%      # | Defined in
          dbname:   %database_name%      # | parameters.ini
          user:     %database_user%      # |
          password: %database_password%  # <
        another:
          driver:   %database2_driver%    # <
          host:     %database2_host%      # |
          port:     %database2_port%      # | Defined in
          dbname:   %database2_name%      # | parameters.ini
          user:     %database2_user%      # |
          password: %database2_password%  # <

Then you define your multiple entity managers as so

doctrine:
    orm:
        default_entity_manager:   default
        entity_managers:
            default:
                connection:       default
                mappings:
                    AcmeDemoBundle: ~
                    AcmeStoreBundle: ~
            another:
                connection:       another
                mappings:
                    AcmeCustomerBundle: ~

then in your action you can use the following to get the correct entity manager :

$em = $this->get('doctrine')->getEntityManager('default');
$em = $this->get('doctrine')->getEntityManager('another');

depending on which entity manager you required


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...