问题
I have two GraphQL type:
type Author {
id: String!
name: String!
}
type Book {
id: String!
author: Author!
name: String!
}
In my database, it is implemented by a foreign key inside the books table:
table authors (pseudo code)
`id` INTEGER UNSIGNED
`name` STRING
table books (pseudo code)
`id` INTEGER UNSIGNED
`author_id` INTEGER UNSIGNED REFERENCE `authors.id`
`name` STRING
So when I resolve a GraphQL query like:
query allTheBooks {
id
name
author {
id
name
}
}
I would like to do only one SELECT
SQL query like:
SELECT books.id, books.name, authors.id, authors.name
FROM books
LEFT JOIN authors ON authors.id = books.author_id
Instead of the current:
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]
[...]
Is there a way to know which "child fields" are queried in a GraphQL resolver ?
Thank you in advance for your answer !
回答1:
I just discovered that in the fourth parameter gived at the resolver, there where an array of the queried fields: info.fieldNodes[0].selectionSet.selections
.
I didn't found any documentation about this, and I wonder what represent the fieldNodes
array... (and dont like to access the first element that way without knowing it...).
The selections
object contains an array like this:
[
{
kind: 'Field',
alias: undefined,
name: { kind: 'Name', value: 'id', loc: [Object] },
arguments: [],
directives: [],
selectionSet: undefined,
loc: { start: 36, end: 38 }
},
{
[...]
},
...
]
Here, the value: 'id'
match the name of the queried field of the related author.
If I go a level deeped, the selectionSet: undefined
becomes an object and the pattern repeat itself recursively...
来源:https://stackoverflow.com/questions/50548188/graphql-how-to-do-a-join-request-instead-of-many-sequential-request