GraphQL部门查询user为空、getDept传参失效及按名称查询问题咨询
问题解决方案
1. 部门列表查询返回空user数组问题
Prisma 默认不会主动加载关联表数据,你可以二选一实现:
方案1:主动在查询中关联用户表
修改departments resolver,增加include参数指定加载关联的user数据:
departments: async (parent, args, context) => { return context.prisma.department.findMany({ include: { user: true // 字段名要和你Prisma schema中定义的关联字段名一致 } }); },
如果需要getDept也返回用户数据,在对应的findUnique参数里也加上相同的include配置即可。
方案2:按需加载用户数据(更符合GraphQL规范)
新增Department类型的字段resolver,只有当客户端请求user字段时才会触发查询,避免不必要的数据库关联查询:
// 和Query同级添加如下配置 Department: { user: async (parent, args, context) => { return context.prisma.user.findMany({ where: { departmentId: parent.id } // departmentId替换成你用户表关联部门表的外键字段名 }) } }
2. getDept接口传参无法匹配ID问题
绝大多数场景是类型不匹配导致的:
- 如果你MySQL的部门id字段是INT自增类型,GraphQL传过来的
args.id是字符串类型,直接传入findUnique会因为类型不匹配查不到数据,需要手动转成数字类型:
修改后的getDeptresolver:
getDept: async (parent, args, context) => { return context.prisma.department.findUnique({ where: { id: Number(args.id) }, include: { user: true } // 可选,需要返回用户数据就加 }); },
- 请同步检查你的查询请求写法是否正确,GraphQL Playground 示例查询写法参考:
query GetDept($id: ID!) { getDept(id: $id) { id name user { id name } } } // 下方变量栏填入 { "id": 1 }
3. 使用部门名称name作为查询参数实现
可以实现,分两种情况处理:
情况1:部门名称是唯一值
首先在你的Prisma schema中给Department的name字段加@unique约束,执行迁移后修改代码:
- 修改GraphQL schema:
type Query { departments: [Department!]! getDept(id: ID!): Department! getDeptByName(name: String!): Department! # 新增查询 }
- 添加对应的resolver:
getDeptByName: async (parent, args, context) => { return context.prisma.department.findUnique({ where: { name: args.name }, include: { user: true } }) }
情况2:部门名称允许重复
不用加unique约束,直接使用findFirst查询即可:
getDeptByName: async (parent, args, context) => { return context.prisma.department.findFirst({ where: { name: args.name }, include: { user: true } }) }
内容的提问来源于stack exchange,提问作者ranran212
相关产品推荐
相关产品推荐

