简体   繁体   中英

How to select the connection to database when I use console in symfony2

I have two databases, (MySQL and Oracle), I did the connection betweek sf2 and both databases, here is my config.yml file:

doctrine:
dbal:
    default_connection:   default
    connections:
        default:
            driver:   "%database_driver%"
            host:     "%database_host%"
            port:     "%database_port%"
            dbname:   "%database_name%"
            user:     "%database_user%"
            password: "%database_password%"
            charset:  UTF8
            # if using pdo_sqlite as your database driver, add the path in parameters.yml
            # e.g. database_path: "%kernel.root_dir%/data/data.db3"
            # path:     "%database_path%"
        sysman:
            driver:   %database_driver2%
            host:     %database_host2%
            port:     %database_port2%
            dbname:   %database_name2%
            user:     %database_user2%
            password: %database_password2%
            charset:  UTF8

My question is, how can I run console command on the second database (Oracle), commands like (doctrine:database:create ...), and thanks

Use the --connection parameter:

php app/console doctrine:database:create --connection=default

or

php app/console doctrine:database:create --connection=sysman

You should first read a tutorial about commands and how to pass options and parameters to the commands. And how to distinguish between an option and a parameter.

If you want to make your own commands...

You will probably want to make it like this - if you do not pass an option (you will use the default database), if you pass it, you will make sure it is a valid option, and use the passed database connection name.

Doctrine is not tightly coupled with Mysql, you can use almost all most common available databases.

Also note, commands are container aware. That means you commands can access container, though which you have access to your services, such as doctrine:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $connection $input->getArgument('connection');
    # Validate connection argument here and use it below

    $container = $this->getContainer();
    $em = $container->get('doctrine')->getManager(); // default db
    $em = $container->get('doctrine')->getManager('sysman'); // another

    return 1;
}

I wrote the code without testing, excuse me for any mistake I might have done.

php app/console doctrine:mapping:info --em=default (same without em option)
php app/console doctrine:mapping:info --em=sysman

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