Yii2项目中多个数据库的设计
前几天接到个需求,有个多成员单位的应用,共用一套代码,但数据库是各自的;在登录时选择不同的成员单位,此应用就连接不同的数据库。
思路:前端使用ajax 修改后端session($_SESSION['mydb']),然后后端根据$_SESSION['mydb']选择数据库;
直接上代码:
//某个控制器 public function actionSetDb() { $request = Yii::$app->request->post(); $_SESSION['mydb'] = 'db_'.$request['id'];//对应成员单位各自的数据库 注意:vendor\yiisoft\yii2\base\Application.php 491行 调用 //Yii::getLogger()->log('新端口'.print_r($request,true), Logger::LEVEL_INFO); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//设定返回json格式 return ['msg'=>"成功"]; } //\common\config\main-local.php return [ 'components' => [ 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=xxxx', //'dsn' => 'mysql:host=localhost;dbname=test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', ], 'db_2' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yyyyy', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], ], ]; //\vendor\yiisoft\yii2\base\Application.php 491行 return $this->get('db');改成return $this->get($_SESSION['mydb']); public function getDb() { return $this->get($_SESSION['mydb']); }
此方案缺点:改动了框架的源码。。。哪位有更好的解决方案 请留言😊