Home  >  Article  >  PHP Framework  >  How to modify the database connection in yii2

How to modify the database connection in yii2

王林
王林Original
2020-02-26 11:28:302791browse

How to modify the database connection in yii2

Configure multiple databases:

return [
    // ...
    'components' => [
        // ...
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=example',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    'db2' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=example',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],
    // ...
];

(Recommended tutorial: yii framework)

If applied in your application If there is more than one database, and you need to use a different database connection (DB connection) for your AR class, you can override the yii\db\ActiveRecord::getDb() method:

class Customer extends ActiveRecord{    // ...
    public static function getDb()
    {
            return \Yii::$app->db2;  // 使用名为 "db2" 的应用组件
    }
}

More programming related content , please pay attention to the Introduction to Programming column on the php Chinese website!

The above is the detailed content of How to modify the database connection in yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn