Yii2在运行时设置db连接 [英] Yii2 set db connection at runtime
本文介绍了Yii2在运行时设置db连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Yii2(基本应用程序)web.php中,我将一个NULL数据库连接配置为第二个数据库连接。
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',
],
初始化app()后,我需要填写NULL参数,我从另一个数据库检索的值,以便在模型中进一步使用。
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.
如何在Yii2中实现?
How can i achieve this in Yii2?
推荐答案
没问题,支持
\Yii::$app->db2->close(); // make sure it clean
\Yii::$app->db2->dsn= 'yourdsn';
\Yii::$app->db2->username = 'username';
\Yii::$app->db2->password = 'password';
完成,现在可以使用它
Yii::$app->db2->...
另一种方式:
$connection = new \yii\db\Connection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
$command = $connection->createCommand('SELECT * FROM post')->....;
参考: http://www.yiiframework.com/doc-2.0/yii-db-connection.html
这篇关于Yii2在运行时设置db连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文