GraphQL 如何做一个 JOIN 请求而不是许多顺序请求?



我有两种 GraphQL 类型:

type Author {
id: String!
name: String!
}
type Book {
id: String!
author: Author!
name: String!
}

在我的数据库中,它由 books 表中的外键实现:

表作者(伪代码(

`id` INTEGER UNSIGNED
`name` STRING

表簿(伪代码(

`id` INTEGER UNSIGNED
`author_id` INTEGER UNSIGNED REFERENCE `authors.id`
`name` STRING

因此,当我解析 GraphQL 查询时,例如:

query allTheBooks {
id
name
author {
id
name
}
}

我只想执行一个SELECTSQL查询,例如:

SELECT books.id, books.name, authors.id, authors.name
FROM books
LEFT JOIN authors ON authors.id = books.author_id

而不是当前:

SELECT books.id, books.name, books.author_id
FROM books
SELECT authors.id, authors.name
FROM authors
WHERE author.id = [one the the books.author_id of the first SELECT]
SELECT authors.id, authors.name
FROM authors
WHERE author.id = [one the the books.author_id of the first SELECT]
[...]

有没有办法知道在 GraphQL 解析器中查询了哪些"子字段"?

提前感谢您的回答!

我刚刚发现在解析器给出的第四个参数中,有一个查询字段数组:info.fieldNodes[0].selectionSet.selections.

我没有找到任何关于此的文档,我想知道什么代表fieldNodes数组......(并且不喜欢在不知情的情况下以这种方式访问第一个元素......

selections对象包含如下数组:

[
{
kind: 'Field',
alias: undefined,
name: { kind: 'Name', value: 'id', loc: [Object] },
arguments: [],
directives: [],
selectionSet: undefined,
loc: { start: 36, end: 38 }
},
{
[...]
},
...
]

此处,value: 'id'与相关作者的查询字段的名称匹配。

如果我深入一个层次,selectionSet: undefined就会变成一个对象,模式会递归地重复......

最新更新