我有一个检索用户应用程序的服务,该服务接受可选参数listingId (这是应用程序的关系),并为user.id提供了一个固定的WHERE子句,该子句等于传入的身份验证请求中的一个:
@Injectable()
export class ApplicationsService {
constructor(@Inject(REQUEST) private readonly request: any) {}
async list(listingId?: string) {
return Application.find({
where: {
user: { id: this.request.user.id },
listing: { id: listingId }
},
})
}
}不幸的是,上面的实现返回一个空数组。可能是因为{ listing: { id: undefined } }会导致"IS NULL“查询,对吗?我找到了一个解决方法:
@Injectable()
export class ApplicationsService {
constructor(@Inject(REQUEST) private readonly request: any) {}
async list(listingId?: string) {
return Application.find({
where: {
user: { id: this.request.user.id },
...(listingId && { listing: { id: listingId } }),
},
})
}
}但我正在寻找一种更通用/更好的方法,因为将来我可以有多个可选参数,而不得不像这样传播它们是丑陋的,而且容易出错。更不用说代码是不可读的。
发布于 2020-07-10 01:40:49
一项服务?但是你使用的是什么框架呢?NestJS?它看起来有点像,但并不是很地道。
我建议将TypeORM QueryBuilder用于更复杂的查询,特别是具有大量条件的查询。
请参阅以下网址上的文档:
https://typeorm.io/#/select-query-builder
您可以为了代码的可读性而拆分代码。
例如,从const query = [...].createQueryBuilder('example')开始,然后可以使用各种可用的方法(例如,addSelect()、.where()、andWhere()、.innerJoin()等)有条件地向代码中添加子句,最后以.getOne()、.getRawOne()、.getMany()、< query >D10结束。
Re TypeORM在假设它是如何处理undefined时要小心。如果您希望在find()查询中显式,请查看typeorm包中的Not、IsNull等。
https://stackoverflow.com/questions/62817668
复制相似问题