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.

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



9.8k

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.

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



9.8k
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.

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