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

  1. 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.
  2. Create two MySQL databases named db1 and db2.
  3. Create a table named post in db1, as follows:
    DROP TABLE IF EXISTS 'post'; CREATE TABLE IF NOT EXISTS 'post' ( 'id' INT(10) UNSIGNED ...

Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.