0
0
GraphQLquery~5 mins

One-to-many relationships in GraphQL

Choose your learning style9 modes available
Introduction

One-to-many relationships help connect one item to many related items. This lets us organize data like a list of things belonging to one main thing.

When you want to show all orders made by one customer.
When you need to list all comments under a single blog post.
When you want to display all books written by one author.
When you track all tasks assigned to one employee.
When you store all messages sent in one chat conversation.
Syntax
GraphQL
type Parent {
  id: ID!
  name: String!
  children: [Child!]!
}

type Child {
  id: ID!
  title: String!
  parentId: ID!
}

The parent type has a list field that holds many children.

Each child has a field to link back to its parent.

Examples
This example shows authors with many books.
GraphQL
type Author {
  id: ID!
  name: String!
  books: [Book!]!
}

type Book {
  id: ID!
  title: String!
  authorId: ID!
}
This example shows customers with many orders.
GraphQL
type Customer {
  id: ID!
  name: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  product: String!
  customerId: ID!
}
Sample Program

This query gets one user and all their posts, showing the one-to-many relationship.

GraphQL
type User {
  id: ID!
  username: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  content: String!
  userId: ID!
}

query GetUserWithPosts {
  user(id: "1") {
    id
    username
    posts {
      id
      content
    }
  }
}
OutputSuccess
Important Notes

Always include the list field in the parent type to hold many children.

Use non-null lists ([Child!]!) to ensure the list is always present.

Link children back to the parent with an ID field for easy querying.

Summary

One-to-many connects one item to many related items.

Parent type holds a list of children.

Children link back to their parent with an ID.