Friday, 7 October 2016

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.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts