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

Prisma标量列表能否实现LIKE模糊匹配过滤?

实现Prisma数组字段的模糊匹配过滤

Prisma内置的数组过滤器(如hasSome)仅支持完全匹配数组元素,无法直接实现你需要的「任意过滤词与数组中任意元素模糊匹配」需求。要达成目标,需借助Prisma的原生SQL查询,以下针对主流数据库给出具体实现:

PostgreSQL 场景

PostgreSQL原生支持数组操作,通过unnest将数组转成行数据,再结合LIKE完成模糊匹配:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
const filterArray = ["value11", "value22"];

// 逻辑:检查words数组中是否有元素包含任意过滤词
const result = await prisma.$queryRaw`
  SELECT * FROM "Keywords"
  WHERE EXISTS (
    SELECT 1 FROM unnest("words") AS word
    WHERE ${Prisma.join(filterArray.map(item => `word LIKE '%' || ${item} || '%'`), ' OR ')}
  )
`;

如果你的需求是过滤词包含数组元素(比如示例中value11包含value1),只需调换LIKE的通配符位置:

word LIKE ${item} || '%' -- 前缀匹配,可根据需求调整为 '%' || ${item} 或其他形式

MySQL 场景

Prisma的String[]在MySQL中会存储为JSON数组,可使用JSON_SEARCH函数实现模糊匹配:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
const filterArray = ["value11", "value22"];

// 生成匹配条件:数组中任意元素包含过滤词即命中
const matchConditions = filterArray
  .map(item => `JSON_SEARCH(words, 'one', '%${item}%') IS NOT NULL`)
  .join(' OR ');

const result = await prisma.$queryRaw`
  SELECT * FROM Keywords
  WHERE ${Prisma.raw(matchConditions)}
`;

关键提示

  • 防SQL注入:如果过滤词来自用户输入,必须使用Prisma的参数化方法(如Prisma.join或带参数的Prisma.raw),禁止直接拼接字符串
  • 匹配方向:根据实际业务需求调整LIKE的通配符位置,确保符合预期的模糊匹配逻辑

内容的提问来源于stack exchange,提问作者Anton Belev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:36:32