Multiple database connections and Yii 2.0

后端 未结 4 2175
遥遥无期
遥遥无期 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:18

    First you need to configure your databases like below:

    return [
    'components' => [
        'db1' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,...
            'username' => 'db1username',
            'password' => 'db1password',
        ],
        'db2' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=db2name', // Maybe other DBMS such as psql (PostgreSQL),...
            'username' => 'db2username',
            'password' => 'db2password',
        ],
    ],
    ];
    

    Then you can simply:

    // To get from db1
    Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
    
    // To get from db2
    Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()
    

    If you are using an active record model, in your model you can define:

    public static function getDb() {
        return Yii::$app->db1;
    }
    
    //Or db2
    public static function getDb() {
        return Yii::$app->db2;
    }
    

    Then:

    If you have set db1 in the getDb() method, the result will be fetched from db1 and so on.

    ModelName::find()->select('*')->all();
    

提交回复
热议问题