Multiple DB Connections in Phalcon


Nov '14

Dec '14

1

2259

0


Thien
31.3k
edited Nov '14
Nov '14

In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Model needs to connect to the database it requests the “db” service in the application’s services container.

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

Specify Connection

Now that we have a 2nd database connection setup - how do we use it in code?In the Initialize method, we define the connection service db you want to it for the model:

    <?php

  class Robots extends \Phalcon\Mvc\Model
  {

      public function initialize()
      {
          $this->setConnectionService('dbPostgres');
      }

  }
edited Dec '14
Dec '14

I am actually using two mysql databases for a project, and JOIN won't work unless you add setSchema in the initialize method.

<?php

class Robots extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        $this->setConnectionService('dbName');
        $this->setSchema('dbName');
    }

}

Thien
31.3k