Multiple database connections in Yii 2.0

The world is changing with the emerging digital trends right from ordering food online, banking, online shopping to online education, events & much more. All these activities are being possible only due to technology experts who have developed the websites, mobile apps which can carry the load of huge data & functionalities. While creating such kinds of complex web applications, back end developers often need to deal with multiple databases at the same time.Sometimes it becomes difficult to manage and handle multiple databases in the same web application.

Yii 2.0 framework provides a simple way to connect your web application with multiple databases.Yii provides multiple database connections by default.  Yii components are used to make a connection between your database and models.

If you are using advanced Yii framework, you just need to follow few steps:

Step 1: Open main-local.php file from your-application/common/ folder.

Add following lines into your file –

return [

‘components’ => [

‘db’ => [

‘class’ =>’yii\db\Connection’,

‘dsn’ =>’mysql:host=localhost;dbname=database1′,

‘username’ =>’db1username’,

‘password’ =>’db1password’,


‘db1’ => [

‘class’ =>’yii\db\Connection’,

‘dsn’ =>’mysql:host=localhost;dbname=database2′,

‘username’ =>’db2username’,

‘password’ =>’db2password’,


‘db2’ => [

‘class’ =>’yii\db\Connection’,

‘dsn’ =>’mysql:host=localhost;dbname=database3′,

‘username’ =>’db3username’,

‘password’ =>’db3password’,




In this manner, you can add multiple databases that are needed for your application.


Step 2: If you are using active record model, then you need to define the database connection in your model using getDb () method,

<?php namespace frontend\models; use Yii; classYourModel extends \yii\db\ActiveRecord{public static function tableName(){return ‘table_name’;} publicfunctiongetDb(){returnYii::$app->db1;}} ?>

If you do not define any connection in getDb (), it takes ‘db’ as default from your main-local.php configuration file.

Step 3:

If you want to access your database from controller, you simply need to add the following line while querying your database,

$connection = \Yii::$app->db1; $command = $connection->createCommand(“Your sql command”); $result = $command->execute();


A single database is usually not enough to supportthe requirements of large and complex web applications.Thus, Yii 2.0 framework provides a simple yet useful way for back end developers to connect a web application with multiple databases.

Share this: