3

i have to database namely master and xyz ,in that i required to connect both database in application . so is it possible to connect multiple database in one application and yes then how.?

2 Answers2

14

Set your connections in DI:

//This service returns a MySQL database
$di->set('dbMaster', function() {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
     return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

In your models choose the connection:

public function initialize()
{
    $this->setConnectionService('dbMaster');
    //or
    $this->setConnectionService('dbSlave');
}
crada
  • 379
  • 2
  • 6
  • 1
    but using this coding i can use only one database at time in model but i want to use both database in same model – Bhavin Solanki Mar 06 '14 at 05:14
  • 1
    I am sorry, but I am not sure what you try to achieve. Probably you have your reasons, but as an advice, you should try to keep the model, for one connection and one table. If you can explain better what is your goal, maybe I or someone else can help you with the right solution. – crada Mar 06 '14 at 09:20
5

Another way to do this, using the same configuration

//This service returns a MySQL database
$di->set('dbMaster', function() {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
         "host" => "localhost",
         "username" => "",
         "password" => "",
         "dbname" => ""
    ));
});

In your model set

public function initialize()
{
    $this->setReadConnectionService('dbSlave');
    $this->setWriteConnectionService('dbMaster');

    $this->setSource('table_name');
}

If you use transaction, remember in the injector dependency to change

$di->set('dbMaster' ....

For

$di->setShared('dbMaster'....

And the rest is the same