如何通过GraphQL查询获取两张关联SQL表的age与name字段
如何通过GraphQL查询关联SQL表的age和name字段
要实现从关联的SQL表a和b中获取age和name字段,需要完成GraphQL Schema定义、Resolver函数实现、编写查询语句这三个核心步骤,以下是具体操作:
1. 定义GraphQL Schema
首先要基于你的SQL表结构,定义对应的GraphQL类型和查询入口,明确表之间的关联关系:
# 对应SQL表a的GraphQL类型 type A { id: ID! age: Int! # 关联表b的记录:一个A可以对应多个B(因为b.pid关联a.id) bs: [B!]! } # 对应SQL表b的GraphQL类型 type B { id: ID! pid: ID! name: String! # 关联表a的记录:一个B对应一个A a: A! } # 查询入口,定义可执行的查询操作 type Query { # 根据ID查询单个A及其关联的B getA(id: ID!): A # 根据ID查询单个B及其关联的A getB(id: ID!): B # 查询所有A及其关联的B getAllAs: [A!]! # 查询所有B及其关联的A getAllBs: [B!]! }
2. 实现Resolver函数
Resolver是GraphQL和数据库之间的桥梁,负责处理具体的数据库查询逻辑。以下是基于Node.js+PostgreSQL的示例(你可以根据所用语言/数据库调整):
// 假设context中包含数据库连接实例context.db const resolvers = { // 处理A类型中bs字段的关联查询 A: { bs: async (parent, _, context) => { // parent是当前查询到的A对象,取其id作为条件查询表b const result = await context.db.query( 'SELECT id, pid, name FROM b WHERE pid = $1', [parent.id] ); return result.rows; } }, // 处理B类型中a字段的关联查询 B: { a: async (parent, _, context) => { // parent是当前查询到的B对象,取其pid作为条件查询表a const result = await context.db.query( 'SELECT id, age FROM a WHERE id = $1', [parent.pid] ); return result.rows[0]; } }, // 处理Query中的查询操作 Query: { getA: async (_, { id }, context) => { const result = await context.db.query( 'SELECT id, age FROM a WHERE id = $1', [id] ); return result.rows[0]; }, getB: async (_, { id }, context) => { const result = await context.db.query( 'SELECT id, pid, name FROM b WHERE id = $1', [id] ); return result.rows[0]; }, getAllAs: async (_, __, context) => { const result = await context.db.query('SELECT id, age FROM a'); return result.rows; }, getAllBs: async (_, __, context) => { const result = await context.db.query('SELECT id, pid, name FROM b'); return result.rows; } } };
如果使用ORM工具(比如Prisma),可以大幅简化Resolver的编写,不需要手动拼接SQL:
Prisma Schema示例
model A { id Int @id @default(autoincrement()) age Int bs B[] // 关联表B的记录 } model B { id Int @id @default(autoincrement()) pid Int name String a A @relation(fields: [pid], references: [id]) // 关联表A }
Prisma版本Resolver
const resolvers = { A: { bs: (parent) => prisma.a.findUnique({ where: { id: parent.id } }).bs() }, B: { a: (parent) => prisma.b.findUnique({ where: { id: parent.id } }).a() }, Query: { getA: (_, { id }) => prisma.a.findUnique({ where: { id } }), getB: (_, { id }) => prisma.b.findUnique({ where: { id } }), getAllAs: () => prisma.a.findMany(), getAllBs: () => prisma.b.findMany() } };
3. 编写GraphQL查询语句
根据你的需求,选择对应的查询方式:
方式1:查询单个A的age及其关联B的name
query GetAWithRelatedNames { getA(id: "1") { // 替换为实际的A表id age bs { name } } }
方式2:查询单个B的name及其关联A的age
query GetBWithRelatedAge { getB(id: "1") { // 替换为实际的B表id name a { age } } }
方式3:查询所有A的age及其关联B的name
query GetAllAsWithNames { getAllAs { age bs { name } } }
内容的提问来源于stack exchange,提问作者tej
相关产品推荐
相关产品推荐

