1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import { RelationCountLoader } from 'typeorm/query-builder/relation-count/RelationCountLoader'; import { RelationIdLoader } from 'typeorm/query-builder/relation-id/RelationIdLoader'; import { RawSqlResultsToEntityTransformer } from 'typeorm/query-builder/transformer/RawSqlResultsToEntityTransformer';
async findAll(userId: number) { const qb = this.repo .createQueryBuilder('e_record') .addSelect('avg(e_record.score)', 'averageScore') .where('userId = :userId', { userId }) .orWhere('e_record.relTeacherId = :userId', { userId }) .leftJoinAndSelect( 'e_record.exam_room', 'e_room', 'e_room.id = e_record.examRoomId', ) .leftJoinAndSelect( 'e_room.for_classes', 'classes', 'classes.id = e_room.for_classes', ) .leftJoinAndSelect( 'e_record.exam_paper', 'e_paper', 'e_paper.id = e_record.examPaperId', ) .groupBy('e_record.relTeacherId'); const rawResults = await qb.getRawMany(); const avgScoreList = rawResults.map((entity) => ({ id: entity.e_record_id, score: entity.averageScore, })); const connection = this.repo.manager.connection; const queryRunner = connection.createQueryRunner(); const relationIdLoader = new RelationIdLoader( connection, queryRunner, qb.expressionMap.relationIdAttributes, ); const relationCountLoader = new RelationCountLoader( connection, queryRunner, qb.expressionMap.relationCountAttributes, ); const rawRelationIdResults = await relationIdLoader.load(rawResults); const rawRelationCountResults = await relationCountLoader.load(rawResults); const transformer = new RawSqlResultsToEntityTransformer( qb.expressionMap, connection.driver, rawRelationIdResults, rawRelationCountResults, queryRunner, ); const transformed = transformer.transform( rawResults, qb.expressionMap.mainAlias, ); return transformed.map((entity) => { const avgScore = avgScoreList.find((score) => score.id === entity.id)?.score || 0; return { ...entity, avgScore, }; }); }
|