yii2 使用多个数据库的案例
配置:
'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=ip;dbname=dbname', 'username' => 'username', 'password' => 'pwd', 'charset' => 'utf8', ], 'db2' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=ip;dbname=dbname2', 'username' => 'username', 'password' => 'pwd', 'charset' => 'utf8', ], ],
模型:
class Norders extends BaseModel { /** * @inheritdoc */ public static function tableName() { return 'norders'; } public static function getDb() { //var_dump(Yii::$app->get('db2'));die; return Yii::$app->get('db2'); //dbresult 就是你自己的配置的DB 名字 } }
控制器:
public function actionAddNorders(){ $data = Norders::find()->all(); var_dump($data);die; }