3

我必须数据库即master和xyz,因为我需要在应用程序中连接这两个数据库。那么是否可以在一个应用程序中连接多个数据库,是的,那么如何。?

4

2 回答 2

14

在 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" => ""
    ));
});

在您的模型中选择连接:

public function initialize()
{
    $this->setConnectionService('dbMaster');
    //or
    $this->setConnectionService('dbSlave');
}
于 2014-03-05T14:48:40.060 回答
5

另一种方法是使用相同的配置

//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" => ""
    ));
});

在您的模型集中

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

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

如果你使用事务,记得在注入器依赖中改变

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

为了

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

其余的都是一样的

于 2014-03-18T14:13:36.560 回答