如何在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
相关产品推荐
相关产品推荐

