Bidirectional relationships let you connect two types so you can easily find related data from either side.
0
0
Bidirectional relationships in GraphQL
Introduction
When you want to see all posts written by an author and also find the author of a post.
When you have customers and orders, and want to find orders from a customer or the customer for an order.
When modeling friends in a social app, so you can find who a user is friends with and who has that user as a friend.
When you want to keep data connected both ways for easy navigation in your app.
Syntax
GraphQL
type Author {
id: ID!
name: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: Author!
}Each type has a field pointing to the other type.
Lists (like posts) show many related items; single fields (like author) show one related item.
Examples
A user can have many friends, and each friend is also a user. This is a bidirectional relationship within the same type.
GraphQL
type User {
id: ID!
name: String!
friends: [User!]!
}Customers have many orders, and each order belongs to one customer.
GraphQL
type Customer {
id: ID!
orders: [Order!]!
}
type Order {
id: ID!
customer: Customer!
}Sample Program
This query fetches an author by ID and lists all their post titles, showing how the bidirectional link works.
GraphQL
type Query {
author(id: ID!): Author
}
type Author {
id: ID!
name: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: Author!
}
# Sample query to get an author and their posts
query {
author(id: "1") {
name
posts {
title
}
}
}OutputSuccess
Important Notes
Bidirectional relationships help keep data connected and easy to navigate.
Be careful to avoid infinite loops when querying both sides deeply.
Use lists for many related items, and single fields for one-to-one links.
Summary
Bidirectional relationships connect two types so you can find related data from either side.
They make your data easier to explore and use in queries.
Always define matching fields on both types to keep the connection clear.