Yii2 同一用户多条设备映射记录如何在GridView聚合展示在用设备
现有结构适配判断
当前UserEquipmentMapping表为单记录单设备关联设计(单条映射仅laptop_id/display_id/phone_id三个外键中的1个非空),这也是原有GridView拆分单用户为多行的根本原因。两个需求无需修改原有业务表结构,仅通过调整查询逻辑、渲染规则即可落地。
前置说明:你描述的映射表字段中未提及用户关联字段,实际实现时需在
UserEquipmentMapping表中补充user_id字段关联用户表,这是按用户维度聚合的核心前提。
需求1:Index页按用户聚合展示在用设备
1. 查询层改造
不再直接对映射表做全量查询,通过条件聚合按用户维度分组,仅提取end_date IS NULL(当前在用)的设备型号,拼接为单行结果:
在UserEquipmentMappingSearch模型中重写搜索方法,参考代码:
// 先声明聚合查询用到的虚拟属性,供GridView识别 public $current_display_model; public $current_phone_model; public $current_laptop_model; public function search($params) { $query = self::find() ->select([ // 保留用户唯一标识字段用于分组和渲染 'user_id', 'username', // 条件聚合:仅当记录关联显示器、且未失效时取对应型号 'current_display_model' => "MAX(CASE WHEN display_id IS NOT NULL AND end_date IS NULL THEN display.display_model ELSE NULL END)", // 条件聚合:仅当记录关联办公电话、且未失效时取对应型号 'current_phone_model' => "MAX(CASE WHEN phone_id IS NOT NULL AND end_date IS NULL THEN phone.phone_model ELSE NULL END)", // 条件聚合:仅当记录关联笔记本、且未失效时取对应型号 'current_laptop_model' => "MAX(CASE WHEN laptop_id IS NOT NULL AND end_date IS NULL THEN laptop.laptop_model ELSE NULL END)", ]) ->leftJoin(Display::tableName(), Display::tableName().'.id = '.self::tableName().'.display_id') ->leftJoin(Phone::tableName(), Phone::tableName().'.id = '.self::tableName().'.phone_id') ->leftJoin(Laptop::tableName(), Laptop::tableName().'.id = '.self::tableName().'.laptop_id') ->where([self::tableName().'.end_date' => null]) // 过滤掉已失效的历史记录 ->groupBy(['user_id', 'username']); // 按用户维度分组 $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => ['pageSize' => 20], ]); // 搜索条件加载逻辑保持原有不变 $this->load($params); return $dataProvider; }
初学者注意:因为单条映射仅关联1类设备,聚合时必须用
MAX()包裹条件判断的型号字段,否则MySQL会返回随机的聚合值,导致展示结果错乱。
2. GridView渲染调整
Index视图中的GridView直接对应聚合后的字段配置即可,无需额外处理空值:
GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'username', // 用户名列 'current_display_model', // 当前在用显示器列 'current_phone_model', // 当前在用办公电话列 'current_laptop_model', // 当前在用笔记本列 [ 'class' => 'yii\grid\ActionColumn', 'template' => '{view}', 'urlCreator' => function($action, $model) { // 操作列直接跳转对应用户的历史设备详情页 return ['user-equipment/view', 'user_id' => $model['user_id']]; } ] ] ]);
需求2:用户详情页展示全量历史分配记录
1. 关联方法前置准备
先在UserEquipmentMapping模型中定义好三类设备的关联方法,方便后续取值:
// 关联显示器表 public function getDisplay() { return $this->hasOne(Display::class, ['id' => 'display_id']); } // 关联电话表 public function getPhone() { return $this->hasOne(Phone::class, ['id' => 'phone_id']); } // 关联笔记本表 public function getLaptop() { return $this->hasOne(Laptop::class, ['id' => 'laptop_id']); }
2. 控制器查询逻辑
详情页不做聚合,直接按user_id过滤所有映射记录,不对end_date做限制,保证历史记录全部展示:
public function actionView($user_id) { // 查询该用户所有历史设备记录,按分配时间倒序 $historyQuery = UserEquipmentMapping::find() ->where(['user_id' => $user_id]) ->orderBy(['start_date' => SORT_DESC]); $historyDataProvider = new ActiveDataProvider([ 'query' => $historyQuery, 'pagination' => ['pageSize' => 15], ]); return $this->render('view', [ 'userInfo' => User::findOne($user_id), // 加载用户基础信息 'historyDataProvider' => $historyDataProvider, ]); }
3. 详情页渲染
在视图中用单独的GridView渲染历史记录,增加状态标识区分在用/已失效设备:
// 顶部展示用户基础信息 echo '<h3>用户:'.$userInfo->username.' 的设备分配记录</h3>'; GridView::widget([ 'dataProvider' => $historyDataProvider, 'columns' => [ [ 'attribute' => 'start_date', 'label' => '分配生效时间' ], [ 'attribute' => 'end_date', 'label' => '分配状态', 'value' => function($model) { // 失效时间为空则标注当前在用 return empty($model->end_date) ? '<span class="text-success">当前在用</span>' : '已失效,失效时间:'.$model->end_date; }, 'format' => 'raw' ], [ 'label' => '设备类型', 'value' => function($model) { if(!empty($model->display_id)) return '显示器'; if(!empty($model->phone_id)) return '办公电话'; if(!empty($model->laptop_id)) return '笔记本电脑'; return '未知设备'; } ], [ 'label' => '设备型号', 'value' => function($model) { if(!empty($model->display_id)) return $model->display->display_model; if(!empty($model->phone_id)) return $model->phone->phone_model; if(!empty($model->laptop_id)) return $model->laptop->laptop_model; return '-'; } ] ] ]);
扩展适配提示
如果后续需要支持单用户同时持有多台同类型设备(比如2台显示器),仅需把聚合查询中的MAX()替换为GROUP_CONCAT(),即可将同类型的多个型号用逗号拼接展示,无需调整原有表结构。
内容的提问来源于stack exchange,提问作者Liviu

