A
A
Andrey2019-10-23 08:28:35
Yii
Andrey, 2019-10-23 08:28:35

How to painlessly replace one table from another database in Yii2?

Kind. Sorry for the clumsy language of the question.
I am writing an app in YII2. Made 2 DB. One test, which I torture, the other, which is already being conducted on real data.
There is a table with a config. When adding a thread of a new config line to one of the databases, you have to recreate it in another.
How can I painlessly make a connection to another database of this particular table? The table is filled in manually.
Many lines of code have been written, and this table is used by me in almost every calculation. Unfortunately, I do not want to shovel the entire code.
After a cursory reading of the manuals on this topic, I realized that it is easier to leave everything as it is.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis, 2019-10-23
@skobanev

Answer from SO

return [
'components' => [
    'db1' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db1name', 
        'username' => 'db1username',
        'password' => 'db1password',
    ],
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db2name', 
        'username' => 'db2username',
        'password' => 'db2password',
    ],
],
];

QueryBuilder:
Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll();
Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll();

ActiveRecord
public static function getDb() {
    return Yii::$app->db2;
    // return Yii::$app->db1;
}

I
Ivan Shumov, 2019-10-23
@inoise

For this, hands are generally torn off. If you have a configuration in the database so that users or admins can change it - okay, but then you shouldn’t worry about it, and the code should be organized so that it’s fashionable to test it once and forget it.
If this is some kind of internal configuration of the application, then two questions pop up: why not migrations and why not at all in the configuration itself.
If all this does not make you think, then two things remain: accept the fact that the test database should not affect the production and the fact that the only adequate option to get data from the sales is to dump the database and deploy it to the test server

A
Alexander Verbitsky, 2021-06-04
@VerbAlexVlad

return [
'components' => [
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db2name', 
        'username' => 'db2username',
        'password' => 'db2password',
    ],
],
];

QueryBuilder:
(new \yii\db\Query)->select('*')->from('tbl_name')->createCommand(Yii::$app->db2)->queryAll()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question