如何在NestJS+TypeORM+SQL Server中实现类似MySQL LIKE的全字符串查询
实现TypeORM中licenseKey的模糊查询
我需要通过licenseKey字段的部分内容,查询Beta数据库中Keys表的完整记录,目标是实现如下SQL的查询效果:
SELECT * FROM KEYS WHERE licenseKey LIKE "%XYZ%"
当前控制器代码如下:
@Get('getByLicenseKey/:licenseKey') async getByLicenseKey(@Param('licenseKey') licenseKey: string) { console.log('dsaadfad'); return this.licenseKeyService.getKeyByLicenseKey(licenseKey); }
服务层代码:
async getKeyByLicenseKey(licenseKey: string): Promise<keys[]> { return await this.keyRepo.find({ licenseKey: Like(`${licenseKey}`) }); }
问题解决
当前服务层代码未在查询参数前后添加通配符%,无法实现模糊匹配。修改服务层代码,在Like函数的参数前后拼接%即可:
async getKeyByLicenseKey(licenseKey: string): Promise<keys[]> { return await this.keyRepo.find({ licenseKey: Like(`%${licenseKey}%`) }); }
修改后,TypeORM会自动生成包含%的LIKE查询语句,与目标SQL效果一致,能够匹配所有包含传入licenseKey片段的记录。
内容的提问来源于stack exchange,提问作者Ronak Kansagra
相关产品推荐
相关产品推荐

