Defining and using multiple DB connections
Multiple database connections are not used very often for new standalone web applications. However, when you are building an add-on application for an existing system, you will most probably need another database connection.
From this recipe, you will learn how to define multiple DB connections and use them with DAO, Query Builder, and Active Record models.
Getting ready
Create a new application using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
Create two MySQL databases named
db1
anddb2
.Create a table named post in
db1
, as follows:DROP TABLE IF EXISTS 'post'; CREATE TABLE IF NOT EXISTS 'post' ( 'id' INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, 'title' VARCHAR(255) NOT NULL, 'text' TEXT NOT NULL, PRIMARY KEY ('id') );
Create a table named
comment
indb2
, as follows:DROP TABLE IF EXISTS 'comment'; CREATE TABLE IF NOT EXISTS 'comment' ( 'id' INT...