How to connect multiple database in Yii2

In this post i will show you how to create multiple databases in yii2.In yii2 configuration you can connect with more than one databases.

Yii2 Multiple database


Step 1: You have to add component of multiple database in your config/main.php file where you defined the connection.

'db'=> [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dbname',
    'username' => 'username',
    'password' => 'password',
    'charset' => 'utf8'
],
'secondDb'=> [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dbname2',
    'username' => 'username',
    'password' => 'password',
    'charset' => 'utf8'
],

Step 2: After defined the multiple database in configuration you have to use it like in controller.

$q = 'SELECT * from table where 1'; //This is sql statement
$result1 = Yii::$app->db->createCommand($q)->queryAll(); // The db is first db instance which is dbname
$result2 = Yii::$app->secondDb->createCommand($q)->queryAll(); //The secondDb is your new second db instance which is dbname2

Or

If your are using the ActiveRecord model then you change the db name like this.

<?php

namespace api\models;

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;

class User extends ActiveRecord
{   
    public static function tableName()
    {
        return 'user';
    }

    public static function getDb()
    {
        return \Yii::$app->get('secondDb'); // second database
    }
}

I hope you like the post if you find any issue related the this configuration please comment below.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular