2 databases Yii2



  • Can I work at the same time with two Yii2 databases? If so, please give me an example!



  • Yeah. Here's a short translation of the English StackOverflow response that will help you. (original questions and answer here: https://stackoverflow.com/questions/27254540/yii-2-0-multiple-database-connection )

    For starters, you need to establish a component for each connection:

    return [
    'components' => [
    'db1' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db1name',
        'username' => 'db1username',
        'password' => 'db1password',
    ],
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db2name',
        'username' => 'db2username',
        'password' => 'db2password',
        ],
    ],
    ];
    

    Then in the code of your application in the models. ActiveRecord You need to redesign the method getDb()

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

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

    Models in which you redesigned the method getDb(), indicating db1 as a connection to the base, will receive data from the db1, and vice versa:

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


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2