0
0
GraphQLquery~5 mins

Many-to-many relationships in GraphQL

Choose your learning style9 modes available
Introduction
Many-to-many relationships let us connect items from two groups where each item can link to many items in the other group. This helps organize complex connections clearly.
When students can enroll in many courses, and courses have many students.
When authors write many books, and books have many authors.
When users follow many topics, and topics have many followers.
When products belong to many categories, and categories include many products.
Syntax
GraphQL
type Student {
  id: ID!
  name: String!
  courses: [Course!]!
}

type Course {
  id: ID!
  title: String!
  students: [Student!]!
}
Use lists (arrays) to show multiple connections on both sides.
GraphQL schema defines types and their fields, including lists for many-to-many links.
Examples
Authors and books have a many-to-many relationship using lists on both sides.
GraphQL
type Author {
  id: ID!
  name: String!
  books: [Book!]!
}

type Book {
  id: ID!
  title: String!
  authors: [Author!]!
}
Users and topics connect many-to-many with arrays showing followers and followed topics.
GraphQL
type User {
  id: ID!
  username: String!
  followedTopics: [Topic!]!
}

type Topic {
  id: ID!
  name: String!
  followers: [User!]!
}
Sample Program
This schema defines students and courses linked many-to-many. The query fetches one student and all their courses.
GraphQL
type Student {
  id: ID!
  name: String!
  courses: [Course!]!
}

type Course {
  id: ID!
  title: String!
  students: [Student!]!
}

# Sample query to get a student and their courses
query {
  student(id: "1") {
    name
    courses {
      title
    }
  }
}
OutputSuccess
Important Notes
Many-to-many relationships require lists on both types to show all connections.
In real apps, a join table or linking type often exists behind the scenes to manage these connections.
GraphQL schema shows the shape of data but actual linking is handled in the backend.
Summary
Many-to-many relationships connect many items from one group to many in another.
Use lists in GraphQL types to represent these connections on both sides.
Queries can fetch linked data easily by following these lists.