php _findfirst,php – 如何在phalcon框架中同时连接多个数据库同时在模型类中使用它们不仅一个...

在我的代码中,我有两个数据库ABC和XYZ.我想在同一模型中使用两个数据库而不是phalcon中的解决方案是什么?如何为此实现多个数据库连接?

解决方法:

//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"

));

});

class Robots extends \Phalcon\Mvc\Model

{

public function initialize()

{

$this->setConnectionService('dbPostgres');

}

}

class Robots extends \Phalcon\Mvc\Model

{

public function initialize()

{

$this->setReadConnectionService('dbSlave');

$this->setWriteConnectionService('dbMaster');

}

}

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');

}

}

$robot = Robots::findFirst('id = 101');

标签:php,database,phalcon

来源: https://codeday.me/bug/20190715/1467388.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值