我必须数据库即master和xyz,因为我需要在应用程序中连接两个数据库。 所以可以在一个应用程序中连接多个数据库,是的,如何。?
答案 0 :(得分:13)
在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');
}
答案 1 :(得分:4)
另一种方法,使用相同的配置
//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'....
其余的是相同的