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

如何在Prisma中使用WHERE LIKE子句通过单查询检索关联师生数据?

可以通过单次Prisma查询实现需求

你完全可以用Prisma的嵌套关联查询+过滤功能,在单次数据库请求中获取目标学校的匹配学生和教师列表,无需拆分两次原生查询,同时还能避免SQL注入风险。

实现代码示例

假设你的School模型有唯一标识字段(比如id),可以这样写:

const query = "Doe";
const schoolId = 1; // 替换为你要查询的学校ID

const schoolWithFilteredMembers = await prisma.school.findUnique({
  where: { id: schoolId },
  include: {
    // 过滤姓名包含query的学生(原逻辑是firstname和lastname都匹配,用AND)
    students: {
      where: {
        AND: [
          { firstname: { contains: query } },
          { lastname: { contains: query } }
        ]
      }
    },
    // 过滤姓名包含query的教师
    teachers: {
      where: {
        name: { contains: query }
      }
    }
  }
});

return schoolWithFilteredMembers;

关键说明

  • contains是Prisma提供的查询操作符,等价于SQL的LIKE '%${query}%',Prisma会自动处理字符串转义,避免原生查询的SQL注入风险。
  • 如果需要通过学校名称而非ID定位目标学校,把findUnique换成findFirst,并修改where条件为{ name: "目标学校名称" }即可。
  • 返回的schoolWithFilteredMembers结构和你原代码返回的对象一致,包含学校本身信息、过滤后的students和teachers数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:05