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

rad*_*ika 3 php database phalcon

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

小智 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"
    ));
});
Run Code Online (Sandbox Code Playgroud)

<?php

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

<?php

    class Robots extends \Phalcon\Mvc\Model
    {

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

    }
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

<?php

$robot = Robots::findFirst('id = 101');
Run Code Online (Sandbox Code Playgroud)