We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Using multiple db in webapi

i want to know how to use 2 db's in single webapi application... i did this

$di->set('db', function () { return new PdoMysql( array( "host" => "localhost", "username" => "root", "password" => "", "dbname" => "db1" ) ); });

$di->set('dbblog', function () { return new PdoMysql( array( "host" => "localhost", "username" => "root", "password" => "", "dbname" => "db2" ) ); });

and in models i do public function initialize() { $this->setSource('wp_posts'); $this->setConnectionService('dbblog'); } but this is not working



17.5k

Have you tried reversing those statements? I would think you need to set the connection to the database that has the correct table before you setSource.



1.6k

reversing means? when i was using single table it's working perfectly



17.5k
Accepted
answer

Do this:

    public function initialize() {
        $this->setConnectionService('dbblog');
        $this->setSource('wp_posts');
    }

Seems that setting the source before setting the connection won't work. I'm not 100% sure... I've never built an app with more than one database, but try setting the connection before setting the source.



1.6k

i did that

$di->set('db', function () { return new PdoMysql( array( "host" => "localhost", "username" => "root", "password" => "", "dbname" => "db1" ) ); });

$di->set('dbblog', function () { return new PdoMysql( array( "host" => "localhost", "username" => "root", "password" => "", "dbname" => "db2" ) ); });

// Create and bind the DI to the application $app = new Micro($di);

and in models: it'z not working public function initialize() {

    $this->setConnectionService('dbblog');
    $this->setSource('wp_posts');
}