【发布时间】:2021-02-04 06:02:07
【问题描述】:
我正在重构一个 koa api 来嵌套,我有点坚持将查询从原生 psql 重构为 typeorm。我有下表、视图和 dto。
@Entity()
export class Challenge {
@PrimaryGeneratedColumn()
id!: number;
@Column()
endDate!: Date;
@CreateDateColumn()
createdAt!: Date;
}
@ViewEntity({
expression: (connection: Connection) => connection.createQueryBuilder()
.select('SUM(cp.points)', 'score')
.addSelect('cp.challenge', 'challengeId')
.addSelect('cp.user', 'userId')
.addSelect('RANK() OVER (PARTITION BY cp."challengeId" ORDER BY SUM(cp.points) DESC) AS rank')
.from(ChallengePoint, 'cp')
.groupBy('cp.challenge')
.addGroupBy('cp.user')
})
export class ChallengeRank {
@ViewColumn()
score!: number;
@ViewColumn()
rank!: number;
@ViewColumn()
challenge!: Challenge;
@ViewColumn()
user!: User;
}
export class ChallengeResultReponseDto {
@ApiProperty()
id!: number;
@ApiProperty()
endDate!: Date;
@ApiProperty()
createdAt!: Date;
@ApiProperty()
score: number;
@ApiProperty()
rank: number;
test() {
console.log("test")
}
}
由于我要返回的对象不是任何实体类型,我有点不知道如何选择它并返回正确的类。我尝试了以下方法:
this.challengeRepository.createQueryBuilder('c')
.select('c.id', 'id')
.addSelect('c.endDate', 'endDate')
.addSelect('c.createdAt', 'createdAt')
.addSelect('cr.score', 'score')
.addSelect('cr.rank', 'rank')
.leftJoin(ChallengeRank, 'cr', 'c.id = cr."challengeId" AND cr."userId" = :userId', { userId })
.where('c.id = :id', { id })
.getRawOne<ChallengeResultReponseDto>();
它返回一个具有正确字段的对象,但它不是类类型“ChallengeResultReponseDto”。如果我尝试调用函数“测试”应用程序崩溃。此外,使用 challengeRepository 但不返回挑战感觉很奇怪,我应该使用连接还是实体管理器来代替它?
【问题讨论】: