加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何在phalcon框架中同时连接多个数据库同时在模型类中使

发布时间:2020-12-13 22:06:19 所属栏目:PHP教程 来源:网络整理
导读:在我的代码中,我有两个数据库ABC和XYZ.我想在同一模型中使用两个数据库而不是phalcon中的解决方案是什么?如何为此实现多个数据库连接? 解决方法 一 ?php//This service returns a MySQL database$di-set('dbMysql',function() { return new PhalconDbAd
在我的代码中,我有两个数据库ABC和XYZ.我想在同一模型中使用两个数据库而不是phalcon中的解决方案是什么?如何为此实现多个数据库连接?

解决方法

<?php

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

//This service returns a PostgreSQL database
$di->set('dbPostgres',function() {
     return new PhalconDbAdapterPdoPostgreSQL(array(
        "host" => "localhost","username" => "postgres","password" => "","dbname" => "invo"
    ));
});

<?php

class Robots extends PhalconMvcModel
{
    public function initialize()
    {
        $this->setConnectionService('dbPostgres');
    }
}

<?php

    class Robots extends PhalconMvcModel
    {

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

    }


????

class Robots extends PhalconMvcModel
{
    /**
     * 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');
    }

}

<?php

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读