Multiple database connections and Yii 2.0

后端 未结 4 2194
遥遥无期
遥遥无期 2020-11-27 14:50

I have two databases, and every database has the same table with the same fields, but how do I get all records from all of two databases at the same time in Yii 2.0?

4条回答
  •  无人及你
    2020-11-27 15:05

    Just to add: I followed the answer provided but still got an error: "Unknown component ID: db"

    After some testing, here is what I discovered: The function getDB is only called AFTER a connection is made to db. Therefore, you cannot delete or rename 'db' in the config file. Instead, you need to let the call to 'db' proceed as normal and then override it afterwards.

    The solution (for me) was as follows:

    In config/web.php add your second database configuration below db as follows:

    'db' => require(__DIR__ . '/db.php'),
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=name',
        'username' => 'user',
        'password' => 'password',
        'charset' => 'utf8',
        'on afterOpen' => function ($event) {
            $event->sender->createCommand("SET time_zone = '+00:00'")->execute();
        },
    ],
    

    DO NOT rename db. Failure to find db will cause an error. You can name db2 whatever you like.

    Now in the model, add the following code:

    class ModelNameHere extends \yii\db\ActiveRecord {
    
       // add the function below:
       public static function getDb() {
           return Yii::$app->get('db2'); // second database
       }
    

    This will now override the default db configuration.

    I hope that helps somebody else.

    Note: you can include the configuration for db2 in another file but you cannot include it in the db.php file (obviously). Instead, create a file called db2.php and call it as you do db:

    'db' => require(__DIR__ . '/db.php'),    
    'db2' => require(__DIR__ . '/db2.php'),
    

    Thanks

提交回复
热议问题