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

如何用Prisma查询ID(数字类型)包含指定值的用户?

实现数字ID的包含式查询(Prisma)

给定Prisma模型:

model User {
  id        Int         @id @default(autoincrement())
  name      String
}

需求是根据变量searchValue查询所有ID(数字类型)包含该值的用户,比如searchValue为10时,返回ID为10、101、1020等的用户,实现类似字符串contains的查询逻辑。

由于Prisma的contains操作符仅支持字符串类型,直接对Int类型的ID使用会报错,因此需要将ID转换为字符串后再进行模糊匹配。以下是可行的实现方案:

方案1:使用$expr构造查询条件

const res = await this.prisma.user.findMany({
  where: this.prisma.$expr`CAST(id AS VARCHAR) LIKE '%${searchValue.toString()}%'`
});

方案2:通过子查询匹配ID

const res = await this.prisma.user.findMany({
  where: {
    id: {
      in: this.prisma.$queryRaw`SELECT id FROM User WHERE CAST(id AS VARCHAR) LIKE '%${searchValue.toString()}%'`
    }
  }
});

说明

  • 核心思路是将数字类型的id通过CAST函数转换为字符串,再用LIKE '%值%'实现包含匹配,效果等同于字符串的contains。
  • 注意要将searchValue转为字符串,避免数字拼接时出现类型问题。

内容的提问来源于stack exchange,提问作者Aharon Ohayon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:45:29