跨数据库关联查询背景
场景设定:所有涉及的数据库必须托管于同一个MySQL实例上。具体包含两个独立的数据库结构:
memory 数据库用于存储常规业务数据,其中包含 user 表,负责记录用户的基本信息。
memory_stat 数据库专门用于存储统计类数据,其中包含 user_stat 表,用于保存用户的各类统计指标。
当前需求是在基于 user 表生成的 GridView 列表中,展示来自 memory_stat 数据库中 user_stat 表的统计数据。
首先需要在 User 模型类中建立与 UserStat 模型的关联关系。
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;
}
],
//其他列
],
]); ?>
随后提出进阶需求:除了展示数据外,还需要支持在 GridView 列表中对这些统计数据进行排序操作以及条件筛选。
如果 user 表和 user_stat 表位于同一个数据库内,通常的处理方式如下:
在 UserSearch 搜索模型中进行相关配置。
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 中配置排序属性,即可实现对数据的正常排序显示。
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
//其他列
[
'label' => '统计数据',
'attribute' => 'data',
'value' => function($model){
return isset($model->stat->data) ? $model->stat->data : null;
}
],
//其他列
],
]); ?>
在 search 表单中添加相应的输入列,即可实现基于这些字段的数据筛选功能。
<?php $form = ActiveForm::begin(); ?>
//其他列
<?= $form->field($model, 'data')?>
//其他列
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
然而实际环境中,user 和 user_stat 表并不在同一个数据库下,这带来了挑战。
执行查询时会触发以下类型的错误提示:
系统抛出 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'memory.user_stat' doesn't exist 异常。被执行的 SQL 语句片段显示为 ...
若要在同一台服务器上的两个不同数据库间进行关联数据查询,标准的纯 SQL 写法应如下所示:
复制代码 代码如下: select a.*,b.* from memory.user as a,memory_stat.user_stat as b where a.id=b.user_id;
Yii2 框架在将 ActiveRecord 转换为 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');
}
以上即为解决 Yii2 跨数据库关联查询、排序及筛选问题的完整方案,希望能为开发者提供有益参考。