php - 如何在 phalcon 框架中同时连接多个数据库在模型类中同时使用而不是只有一个

标签 php database phalcon

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

最佳答案

一个

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

    }

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

关于php - 如何在 phalcon 框架中同时连接多个数据库在模型类中同时使用而不是只有一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22215688/

相关文章:

php - 选择最后插入的记录并分组mysql

php - 确定 PHP 脚本退出位置的最快方法

database - N表有1个:1 relationship with a common table?如何保证唯一性

mysql - Phalcon:MySQL 触发器无法与 Phalcon 框架一起使用

php - Phalcon 无论如何都不会更新记录

PHP Xdebug 调试在第一个断点停止在 VSCode 中工作

php - WooCommerce - 覆盖现有结帐字段上的账单状态和邮政编码

php - 每月佣金计算 PHP

c# - 让 DbDataReader 从结果集的开头重新开始读取

json - 如何在 MySQL 中的 json 列上创建索引?