web.php配置,引入或者直接设置db
我的是引入
$db = require __DIR__ . '/db.php';
components下设置
'db' => $db['db'],
'db2' => $db['db2'],
db.php文件,设置成自己的数据库配置
<?php return [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => env('db_dsn'), 'username' => env('db_username'), 'password' => env('db_password'), 'charset' => env('db_charset'), ], 'db2' => [ 'class' => 'yii\db\Connection', 'dsn' => env('db2_dsn'), 'username' => env('db2_username'), 'password' => env('db2_password'), 'charset' => env('db2_charset'), ], // Schema cache options (for production environment) 'enableSchemaCache' => env('db_enableSchemaCache'), 'schemaCacheDuration' => env('db_schemaCacheDuration'), 'schemaCache' => env('db_schemaCache'), 'enableProfiling'=>true, ];View Code
在模型中使用特定的db连接
public static function getDb() { return Yii::$app->db2; }View Code
测试了一下,如果不设置,默认连接的是db
标签:password,yii2,数据库,charset,db,dsn,env,db2,连接 From: https://www.cnblogs.com/wutianfei/p/18070846