配置方法
<?php return [ 'components' => [ 'db1' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,... 'username' => 'db1username', 'password' => 'db1password', ], 'db2' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=db2name', //maybe other dbms such as psql,... 'username' => 'db2username', 'password' => 'db2password', ], ], ];
直接使用方法
//to get from db1 Yii::$app->db1->createCommand((new \yii\db\Query)->select('')->from('tbl_name'))->queryAll() //to get from db2 Yii::$app->db2->createCommand((new \yii\db\Query)->select('')->from('tbl_name'))->queryAll()
在module里定义
public function getDb() { return Yii::$app->db1; } //Or db2 public function getDb() { return Yii::$app->db2; }
调用方法
ModelName::find()->select('')->all()