N
N
nepster-web2014-04-27 20:56:14
Yii
nepster-web, 2014-04-27 20:56:14

Yii2, how to specify the use of another DB in the model?

you need to use a different database for a particular model.
in the komon in the main.php file I added a new database connection

'components' => [
    'db2' => [
        'class' => '\yii\db\Connection',
        // ...
    ],
]

Now the question is how to tell the model to use a db2 connection.
I was advised something like this:
class Post extends ActiveRecord
{
    public static function getDb()
    {
        return $this->db2;
    }
}

But the problem is that Yii2 scolds $this->db2 for not being there.
I tried a couple more options with self and through Yii::$app
But I still couldn’t agree with the model. Can you please tell me how to explain the model so that it works with db2?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yuri Morozov, 2014-04-27
@nepster-web

return \Yii::$app->get('db2');

A
Alexander N++, 2014-04-27
@sanchezzzhak

According to the idea, you were correctly prompted to override the method for the AR model.
Try return Yii::$app->getComponent('db2');
or so return Yii::$app->db2;

N
nepster-web, 2014-04-27
@nepster-web

I'll update Yii2 now and give it a try.
I just tried Yii::$app->db2 like this , it didn't work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question