You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:41:01