H
H
Head Hunter2017-03-13 17:31:46
Yii
Head Hunter, 2017-03-13 17:31:46

Merging query result from 2 db?

Hello people, who will tell you how you can combine a query from two different databases into one before feeding it to ActiveDataProvider.
The bottom line is there are 2 identical models of 2 different databases? Merge data from two different databases

class HomeStoreAddresses extends BaseActiveRecord
{
    public static function getDb()
    {
        return Yii::$app->home_db;
    }
}

class ClimaStoreAddresses extends BaseActiveRecord
{
    public static function getDb()
    {
        return Yii::$app->clima_db;
    }
}

I know about this option - but it doesn’t work as it should - the request goes to one database
$query1 = HomeStoreAddresses::find()->where([
            'type'      => $type,
            'region_id' => $this->region_id,
        ]);

        $query2 = ClimaStoreAddresses::find()->where([
            'type'      => $type,
            'region_id' => $this->region_id,
        ]);

        $query1->union($query2);
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query1,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

This option is not beautiful and wrong.
$query1 = HomeStoreAddresses::find()->where([
            'type'      => $type,
            'region_id' => $this->region_id,
        ])->all();

        $query2 = ClimaStoreAddresses::find()->where([
            'type'      => $type,
            'region_id' => $this->region_id,
        ])->all();

        $result  = array_merge($query1, $query2);

        $dataProvider = new ArrayDataProvider([
            'key'       =>'id',
            'allModels' => $result,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-03-13
@qonand

In your case, there are two options:
1. Try to configure the ability to work with two databases at the database level. But it all depends on the database, for example, in postgre you can set up dblink and use it to solve your problem (and in some DBMS there is no such possibility at all)
2. Refuse to use ActiveDataProvider (well, or somehow process it yourself) and use ArrayDataProvider those. at the php level, select all the necessary data with two requests, and glue them together using php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question