在我的代码中,我有两个数据库ABC
和XYZ
。我想在同一模型中使用两个数据库而不是phalcon中的解决方案是什么?如何为此实现多个数据库连接?
答案 0 :(得分:12)
一个
<?php
//This service returns a MySQL database
$di->set('dbMysql', function() {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
//This service returns a PostgreSQL database
$di->set('dbPostgres', function() {
return new \Phalcon\Db\Adapter\Pdo\PostgreSQL(array(
"host" => "localhost",
"username" => "postgres",
"password" => "",
"dbname" => "invo"
));
});
2
<?php
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setConnectionService('dbPostgres');
}
}
3
<?php
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setReadConnectionService('dbSlave');
$this->setWriteConnectionService('dbMaster');
}
}
4
class Robots extends Phalcon\Mvc\Model
{
/**
* Dynamically selects a shard
*
* @param array $intermediate
* @param array $bindParams
* @param array $bindTypes
*/
public function selectReadConnection($intermediate, $bindParams, $bindTypes)
{
//Check if there is a 'where' clause in the select
if (isset($intermediate['where'])) {
$conditions = $intermediate['where'];
//Choose the possible shard according to the conditions
if ($conditions['left']['name'] == 'id') {
$id = $conditions['right']['value'];
if ($id > 0 && $id < 10000) {
return $this->getDI()->get('dbShard1');
}
if ($id > 10000) {
return $this->getDI()->get('dbShard2');
}
}
}
//Use a default shard
return $this->getDI()->get('dbShard0');
}
}
5
<?php
$robot = Robots::findFirst('id = 101');
答案 1 :(得分:0)
您不能在同一模型中使用这两个数据库连接。所以:
// Set the connection in the DI
$di->set('database_slave', .....)
$di->set('database_master', .....)
在您的模型中,您只能这样做:
public function initialize()
{
$this->setConnectionService('database_slave');
}
或
public function initialize()
{
$this->setConnectionService('database_master');
}
您不能同时使用两者。如何使模型更灵活,可以做的是扩展基本模型,如下所示:
class MyModel extends \Phalcon\Mvc\Model
{
$connection = '';
public function initialize()
{
// Default to the master connection
$connection = ($this->connection) ? $this->connection : 'database_master';
$this->setConnectionService($connection);
parent::initialize()
}
public function setMyConnection($connection = 'database_master')
{
switch ($connection) {
case 'database_master':
case 'database_slave'
$this->connection = $connection;
break;
default:
$this->connection = 'database_master';
break;
}
}
}
在您的代码中,您可以执行此操作
$mymodel = new MyModel();
$mymodel->setMyConnection('database_slave');
// do other stuff - this model will use the slave now.
如果您确实想要从模型连接到两个数据库,那么您可以使用PHQL并实例化连接到模型中不同数据库的新对象。这是不可取的,但如果这是你想做的事情。
另见: