0
0
GraphQLquery~5 mins

Why relationships model real data in GraphQL

Choose your learning style9 modes available
Introduction

Relationships help connect different pieces of data, just like how things in real life are connected. They make data easier to understand and use.

When you want to show how customers buy products in a store.
When you need to link students to the classes they attend.
When you want to connect employees to the departments they work in.
When you want to track which books belong to which authors.
When you want to organize social media users and their friends.
Syntax
GraphQL
type Author {
  id: ID!
  name: String!
  books: [Book!]!
}

type Book {
  id: ID!
  title: String!
  author: Author!
}
Relationships are shown by linking one type to another using fields.
The exclamation mark (!) means the field is required and cannot be empty.
Examples
This example shows users and their posts connected by relationships.
GraphQL
type User {
  id: ID!
  name: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  content: String!
  author: User!
}
This example shows a many-to-many relationship between students and classes.
GraphQL
type Student {
  id: ID!
  name: String!
  classes: [Class!]!
}

type Class {
  id: ID!
  title: String!
  students: [Student!]!
}
Sample Program

This query gets a customer and all the products they ordered, showing how relationships connect data.

GraphQL
type Customer {
  id: ID!
  name: String!
  orders: [Order!]!
}

type Order {
  id: ID!
  product: String!
  customer: Customer!
}

query GetCustomerOrders {
  customer(id: "1") {
    name
    orders {
      product
    }
  }
}
OutputSuccess
Important Notes

Relationships make data more meaningful by showing connections.

They help avoid repeating the same information in many places.

Using relationships makes it easier to ask questions about connected data.

Summary

Relationships link different data types to reflect real-world connections.

They help organize data clearly and avoid duplication.

GraphQL uses fields to show these connections between types.