eronax59 eronax59 - 3 months ago 19
MySQL Question

How to connect MongoDB and MySQL in same project(app) in Yii/Yii2?

I have a requirement to use two types of databases in single project/app. Now I am confused how to do that. I tried individual and they worked but I don't know how to use it.

Answer

For Yii 2 you can set two db components in configuration like:

'components' => [
    'dbMySQL' => [
        'class' => '\yii\db\Connection',
        'dsn' => 'mysql:...',
        'username' => '...',
        'password' => '...',
        'charset' => 'utf8',
    ],
    'dbMongo' => [
        'class' => '\yii\mongodb\Connection',
        'dsn' => 'mongodb://...',
    ],
],

and then use it where you want

Yii::$app->dbMySQL->...
Yii::$app->dbMongo->...

Remember to override getDb() method in \yii\db\ActiveRecord and \yii\mongodb\ActiveRecord classes to point to these components if you use ActiveRecords.

Comments