在yii项目中,连接多数据库进行操作。
step1:配置main.php 文件。
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=bntake-admin', //数据库1
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test', //数据库test
'username' => 'root',
'password' => 'test',
'charset' => 'utf8',
],
框架默认是 加载db数据库的,如果想要使用db2数据库的数据。
方法一:只需要在现有的model中重写getDb方法。
public static function getDb()
{
return Yii::$app->get('db2');
}
方法二:在gii下,进行设置。
Paste_Image.png