Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 set db connection at runtime

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?

like image 841
Andreas Hinderberger Avatar asked Jan 09 '17 18:01

Andreas Hinderberger


1 Answers

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

like image 131
Ngô Văn Thao Avatar answered Sep 28 '22 14:09

Ngô Văn Thao