【问题标题】:How to connect multiple database in phalcon framework如何在phalcon框架中连接多个数据库
【发布时间】:2014-03-05 12:23:40
【问题描述】:

我必须连接数据库,即 master 和 xyz,因为我需要在应用程序中连接这两个数据库。 那么是否可以在一个应用程序中连接多个数据库,是的,那么如何连接。

【问题讨论】:

    标签: phalcon phalconeye


    【解决方案1】:

    在 DI 中设置连接:

    //This service returns a MySQL database
    $di->set('dbMaster', function() {
         return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "",
            "password" => "",
            "dbname" => ""
        ));
    });
    
    //This service returns a PostgreSQL database
    $di->set('dbSlave', function() {
         return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "",
            "password" => "",
            "dbname" => ""
        ));
    });
    

    在您的模型中选择连接:

    public function initialize()
    {
        $this->setConnectionService('dbMaster');
        //or
        $this->setConnectionService('dbSlave');
    }
    

    【讨论】:

    • 但是使用这种编码我只能在模型中使用一个数据库,但我想在同一个模型中使用两个数据库
    • 很抱歉,但我不确定您要达到什么目的。可能你有你的理由,但作为一个建议,你应该尽量保留模型,一个连接和一个表。如果你能更好地解释你的目标是什么,也许我或其他人可以帮助你找到正确的解决方案。
    【解决方案2】:

    另一种方法,使用相同的配置

    //This service returns a MySQL database
    $di->set('dbMaster', function() {
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "",
            "password" => "",
            "dbname" => ""
        ));
    });
    
    //This service returns a PostgreSQL database
    $di->set('dbSlave', function() {
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
             "host" => "localhost",
             "username" => "",
             "password" => "",
             "dbname" => ""
        ));
    });
    

    在你的模型集中

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

    如果你使用事务,记得在注入器依赖中改变

    $di->set('dbMaster' ....
    

    对于

    $di->setShared('dbMaster'....
    

    其余的都是一样的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多