Yii2 在运行时设置数据库连接

2022-01-07 00:00:00 dynamic database php yii2

在我的 Yii2(基本应用程序)web.php 中,我将 NULL db 连接配置为第二个数据库连接.

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' => 'yiidbConnection',
    '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 yiidbConnection([
    '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

相关文章