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

How to modify the database connection in yii2

王林
Release: 2020-02-26 11:28:30
Original
2880 people have browsed it

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',
        ],
    ],
    // ...
];
Copy after login

(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" 的应用组件
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template