1. 查出全部数据并进行数据筛选过滤
在一对多的情况时,我们想把多的对象集合set进一的里面,需要避免循环sql
java
@Override
public R<List<ExRecord>> getExRecordAll(ExRecord exRecord) {
// 获取用户id
Integer userId = Math.toIntExact(SecurityUtils.getUserId());
List<ExRecord> exRecords = exRecordMapper.selectList(new LambdaQueryWrapper<ExRecord>()
// 根据用户id
.eq(Objects.nonNull(userId), ExRecord::getUserId, userId)
// 根据 试卷类型
.eq(Objects.nonNull(exRecord.getPaperType()), ExRecord::getPaperType, exRecord.getPaperType())
);
// 过滤出全部id
List<Integer> recordIds = exRecords.stream().map(ExRecord::getId).collect(Collectors.toList());
// 过滤答题卡表中的id,并stream流进行分组
Map<Integer, List<ExSheetAnswer>> collect = examSheetAnswerMapper.selectList(Wrappers.<ExSheetAnswer>lambdaQuery()
.in(ExSheetAnswer::getRecordId, recordIds)).stream().collect(Collectors.groupingBy(ExSheetAnswer::getRecordId));
// 根据map id 去赋值
exRecords.forEach(record -> {
record.setSheetAnswers(collect.getOrDefault(record.getId(), Collections.emptyList()));
});
return R.success(exRecords);
}