一個項目根據需要會要求連接多個數據庫,那么在yii2中如何鏈接多數據庫呢?其實很簡單,在配置文件中稍加配置即可完成。
配置方法如下:
打開數據庫配置文件commonconfigmain-local.php,在原先的db配置項下面添加db2,配置第二個數據庫的屬性即可。
實例:
'db' => [ 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=localhost;dbname=hyii2', //數據庫hyii2 'username' => 'root', 'password' => 'pwhyii2', 'charset' => 'utf8', ], 'db2' => [ 'class' => 'yiidbConnection', 'dsn' => 'mysql:host=localhost;dbname=hyii', //數據庫hyii 'username' => 'root', 'password' => 'pwhyii', 'charset' => 'utf8', ],
如上配置就可以完成yii2連接多個數據庫的功能。
相關教程推薦:yii框架