配置多數據庫:
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',
],
],
// ...
];
如果在你的應用中應用了不止一個數據庫,且你需要給你的 AR 類使用不同的數據庫鏈接(DB connection) ,你可以覆蓋掉 yii\db\ActiveRecord::getDb() 方法:
class Customer extends ActiveRecord { // ... public static function getDb() { return \Yii::$app->db2; // 使用名為 "db2" 的應用組件 } }
