Given a GraphQL schema where Author has many Books, what will be the result of this query?
query {
authors {
name
books {
title
}
}
}type Author {
id: ID!
name: String!
books: [Book!]!
}
type Book {
id: ID!
title: String!
authorId: ID!
}
# Sample data:
# authors = [{id: "1", name: "Alice"}, {id: "2", name: "Bob"}]
# books = [{id: "a", title: "GraphQL Basics", authorId: "1"}, {id: "b", title: "Advanced GraphQL", authorId: "1"}, {id: "c", title: "Intro to Databases", authorId: "2"}]Remember that books are linked to authors by authorId.
The query returns each author with their books. Alice has two books, Bob has one.
Which statement correctly describes a one-to-many relationship in a GraphQL schema?
Think about how multiple related items are represented.
One-to-many means one item relates to many items of another type, so the field returns a list.
Which option contains a syntax error in defining a one-to-many relationship?
type Author {
id: ID!
name: String!
books: Book!
}
type Book {
id: ID!
title: String!
authorId: ID!
}One-to-many means one author has many books.
The 'books' field must be a list to represent many books, so it should be '[Book!]!'.
Given a one-to-many relationship between Author and Books, which approach best reduces over-fetching when querying authors with their books?
GraphQL allows selecting exactly what you want.
Selecting only needed fields avoids fetching unnecessary data, improving performance.
Why does this query return authors without their books?
query {
authors {
name
books {
title
}
}
}Schema snippet:
type Author {
id: ID!
name: String!
books: Book
}Check the type of the 'books' field in the schema.
The 'books' field is defined as a single 'Book' instead of a list, so it returns null or one book, not many.