Yii2實現跨mysql數據庫關聯查詢排序功能

背景:在一個mysql服務器上(注意:兩個數據庫必須在同一個mysql服務器上)有兩個數據庫: php

memory (存儲常規數據表) 中有一個 user 表(記錄用戶信息) mysql

memory_stat (存儲統計數據表) 中有一個 user_stat (記錄用戶統計數據)sql

如今在 user 表生成的 GridView 列表中展現 user_stat 中的統計數據

  • 只須要在User的model類中添加關聯數據庫

public function getStat()
{
    return $this->hasOne(UserStat::className(), ['user_id' => 'id']);
}
  • 在GridView就能夠這樣使用來展現統計數據服務器

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [

        //其餘列
        
        [
            'label' => '統計數據',
            'value' => function($model){
                return isset($model->stat->data) ? $model->stat->data : null;
            }
        ],
        
        //其餘列
    ],
]); ?>

如今增長了一個需求,須要在user GridView 列表中對統計數據進行排序和篩選

若 user 和 user_stat 表在同一個數據庫下咱們能夠這樣作:app

  • UserSearch:ide

public $data;
public function rules()
{/*{{{*/
    return [
        ['data'], 'integer'],
        //其餘列
    ];
}/*}}}*/

public function search($params, $onlyActiveUsers = false)
{
    $query = User::find();
    $query->joinWith(['stat']);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'attributes' => [
                //其餘列
                
                'data' => [
                    'asc' => [UserStat::tableName() . '.data' => SORT_ASC],
                    'desc' => [UserStat::tableName() . '.data' => SORT_DESC],
                ],
                
                //其餘列
            ],
            'defaultOrder' => [
                'id' => SORT_DESC,
            ],
        ],
        'pagination' => [
            'pageSize' => 50,
        ],
    ]);

    $this->load($params);

    if (!$this->validate()) {
        $query->where('0=1');
        return $dataProvider;
    }

    $query->filterWhere([
    
        //其餘列
        
        UserStat::tableName() . '.data' => $this->data
    ]);

    return $dataProvider;
}
  • 在GridView就能夠這樣使用來展現統計數據,就能夠排序了this

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [

        //其餘列
        
        [
            'label' => '統計數據',
            'attribute' => 'data',
            'value' => function($model){
                return isset($model->stat->data) ? $model->stat->data : null;
            }
        ],
        
        //其餘列
    ],
]); ?>
  • search 表單中添加如下列就能夠篩選了code

<?php $form = ActiveForm::begin(); ?>
//其餘列 

<?= $form->field($model, 'data')?>

//其餘列
<div class="form-group">
    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

然而現實是殘酷的, user 和 user_stat 表並在同一個數據庫下。

因而就會報出這樣一個錯誤:orm

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'memory.user_stat' doesn't exist
The SQL being executed was: ...

要在兩個數據庫(同一臺服務器)上進行關聯數據查詢,純SQL語句以下:

select a.*,b.* from memory.user as a,memory_stat.user_stat as b where a.id=b.user_id;

Yii2轉化成 SQL 語句時默認不會在代表前添加數據庫名,因而mysql在執行sql語句時就會默認此表在memory數據庫下。

select a.*,b.* from memory.user as a,memory.user_stat as b where a.id=b.user_id;

因而就出現了以上報錯信息。

那麼,如何來解決這個問題呢?

  • 其實很簡單,只須要重寫 user_stat 的 model 類下的 tableName() 方法就能夠了。

// 默認是這樣的
public static function tableName()
{
    return 'user_stat';
}

public static function getDb()
{
    return Yii::$app->get('dbStat');
}
// 只須要在代表前添加數據庫名
public static function tableName()
{
    return 'memory_stat.user_stat';
}

public static function getDb()
{
    return Yii::$app->get('dbStat');
}
// 爲了提升代碼穩定性,能夠這樣寫
public static function tableName()
{
    preg_match("/dbname=([^;]+)/i", static::getDb()->dsn, $matches);
    return $matches[1].'.user_stat';
}

public static function getDb()
{
    return Yii::$app->get('dbStat');
}
相關文章
相關標籤/搜索