Yii2 set db connection at runtime

左心房为你撑大大i 提交于 2019-12-10 09:54:35

问题


In my Yii2 (basic application) web.php I configure a NULL db connection as 2nd database connection.

This needs to be filled with valid parameters which are coming from a record on the main db connection:

'db' => require(__DIR__ . '/db.php'),
'db2' => [
    'class' => 'yii\db\Connection',
    'dsn' => NULL,
    'username' => NULL,
    'password' => NULL,
    'charset' => 'utf8',
],

After initializing the app() i need to fill out the NULL parameters with values that i retrieve from another database to further use it in models.

How can i achieve this in Yii2?


回答1:


No problem, it is supported

\Yii::$app->db2->close(); // make sure it clean
\Yii::$app->db2->dsn= 'yourdsn';
\Yii::$app->db2->username = 'username';
\Yii::$app->db2->password = 'password';

Done, now you can use it

Yii::$app->db2->...

Another way:

$connection = new \yii\db\Connection([
    'dsn' => $dsn,
    'username' => $username,
    'password' => $password,
]);
$connection->open();
$command = $connection->createCommand('SELECT * FROM post')->....;

Refer: http://www.yiiframework.com/doc-2.0/yii-db-connection.html



来源:https://stackoverflow.com/questions/41554390/yii2-set-db-connection-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!