Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Several databases in one project.

Hi, I have a small problem, and I do not know how to solve it.

I want use a several databases mysql in one project, so...

I have such a mysql configuration:

$di->set('db', function() {
    $dbCon = array(
        'host' => '127.0.0.1',
        'username' => 'root',
        'password' => 'root'
    );
    $db = new Mysql($dbCon);
    return $db;
});

A "dbname" is not define because I want use several bases in one project and I want define a "dbname" in a model. For example:

use Phalcon\Mvc\Model;

class MyModel extends Model
{
    //Database selection
}

...Or maybe You have any idea, how to do.

Thanks for every help. :)

<?php

//This service returns a MySQL database
$di->set('db', 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');
    }
}

I know this method,

but I wonder if you can do it in a different way,

or other problem: I have a one sql query that uses several databases, what then?



1.6k
Accepted
answer
edited Jan '15

Service db is only connection provied for you code.

If you have, we say a two databases on one host, with one credentials that have access to them, you can PHQL. If you have a model that connected to a some database, you could use: 1. Plain SQL through di->get("database_service")->query 2. Setting a model db handler inside inner function and then run a PHQL query