6

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 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. This works perfect. I'm using the 1st approach. Now i can do in my models which need only access to the "other" database : public static function getDb() { return Yii::$app->db2; }. This will pull it from the right DB then. As a side not, i've moved all models for the "other" database into a seperate namespace. I think i could also extend ActiveRecord seperately for this namespace, but the getDB in there and then extend all models in that namespace off that AR class.
Thanks a lot, I am using first one and its working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.