如何在phalcon框架中连接多个数据库,同时在模型类中不仅使用一个 [英] How to connect multiple database in phalcon framework at the same time use both in model class not only one

查看:2319
本文介绍了如何在phalcon框架中连接多个数据库,同时在模型类中不仅使用一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my code I have two database ABC and XYZ. I want to use both database in same model than What is the solution for it in phalcon? How to implement multiple database connection for this ?

推荐答案

一个

<?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"
    ));
});

两个

<?php

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->setConnectionService('dbPostgres');
    }
}

<?php

    class Robots extends \Phalcon\Mvc\Model
    {

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

    }




four

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

}

<?php

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

这篇关于如何在phalcon框架中连接多个数据库,同时在模型类中不仅使用一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆