【发布时间】:2021-06-16 01:02:44
【问题描述】:
例如:
const tempResult = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.products', 'product')
.where('product.id = :productId', { productId: option.productId })
.getManyAndCount();
当option.productId的值为''时,我要全部查询。
现在我的代码是这样的:
let tempResult = null;
if (option.productId) {
tempResult = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.products', 'product')
.where('product.id = :productId', { productId: option.productId })
.getManyAndCount();
} else {
tempResult = await this.userRepository.createQueryBuilder('user').getManyAndCount();
}
但是 where 查询太多的时候,代码就这么糟糕了:
let tempResult = null;
if (option.productId && option.organizationId) {
tempResult = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.products', 'product')
.leftJoinAndSelect('user.organization', 'organization')
.where('product.id = :productId', { productId: option.productId })
.where('organization.id = :organizationId', { organizationId: option.organizationId })
.getManyAndCount();
} else if (option.productId) {
tempResult = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.products', 'product')
.where('product.id = :productId', { productId: option.productId })
.getManyAndCount();
} else if (option.organizationId) {
tempResult = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.organization', 'organization')
.where('organization.id = :organizationId', { organizationId: option.organizationId })
.getManyAndCount();
} else {
tempResult = await this.userRepository.createQueryBuilder('user').getManyAndCount();
}
有没有更好的方法在 TypeORM 中结合 QueryBuilder?
【问题讨论】:
-
“但是什么时候where查询太多?”
-
@AWebb 你好,我已经编辑了新的演示代码。
-
无论您使用 TypeORM 做什么,您都将重构您已有的内容。就个人而言,我会为每个场景创建不同的查询,然后从客户端有条件地调用它们。这样,每次调用此查询时,您都不会运行条件。而是针对每个特定场景的客户端条件请求。