3

How to set db connection in yii-db-query?

I have a 3 database connection:

db, db2 and db3

When I used this default Query:

$query = (new \yii\db\Query())
            ->select('*')
            ->from('trans_journal')
            ->all();

It will return an error. The trans_journal is not found, because the trans_journal is from the db2 connection.

And when I used this Query:

$query = (new \yii\db\Query())
            ->select('*')
            ->from('trans_journal')
            ->all(\Yii::$app->db2);

The query will be successfully generated but the problem is it will return an array.

Is there another way to solved this?

2 Answers 2

5

if you are using an active record model, in your model you can redefine properly the getDB function for each model:

  // Model1 

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

  //Model 2
  public function getDb() {
      return Yii::$app->db2;
  }

If you are using command you can set the db in use just in createCommand call

// To get from db1
Yii::$app->db1->createCommand(
          (new \yii\db\Query)->select('col1, col2, ... ')->
                          from('your_table_db1'))->queryAll();

// To get from db2
Yii::$app->db2->createCommand(
            (new \yii\db\Query)->select('col1, col2, ... ')->
                          from('your_table_db2')->queryAll();

The all() method executes the query and returns all results as an array.

You can iterate over the result for get each model eg:

 $results =  Yii::$app->db1->createCommand(
          (new \yii\db\Query)->select('col1, col2, ... ')->
                          from('your_table_db1'))->queryAll();

foreach($results as $key => $value ){
    echo $value->col1;
    // or $value['col1];

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

Comments

2
$query = (new \yii\db\Query())
 ->select('*')
 ->from('trans_journal')
 ->all();

 $dataProvider = new ActiveDataProvider([
        'db' => Yii::$app->get('db2'),
        'query' => $query,
    ]);

$models = $dataProvider->getModels();

Comments

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.