如何在 phalcon 框架中连接多个数据库



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

在 DI 中设置连接:

//This service returns a MySQL database
$di->set('dbMaster', function() {
     return new PhalconDbAdapterPdoMysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
     return new PhalconDbAdapterPdoMysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});

在您的模型中,选择连接:

public function initialize()
{
    $this->setConnectionService('dbMaster');
    //or
    $this->setConnectionService('dbSlave');
}

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

//This service returns a MySQL database
$di->set('dbMaster', function() {
    return new PhalconDbAdapterPdoMysql(array(
        "host" => "localhost",
        "username" => "",
        "password" => "",
        "dbname" => ""
    ));
});
//This service returns a PostgreSQL database
$di->set('dbSlave', function() {
    return new PhalconDbAdapterPdoMysql(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'....

其余的都一样

最新更新