Introduction
Entity references let you connect one piece of data to another. This helps keep data organized and easy to find.
Jump into concepts and practice - no test required
Entity references let you connect one piece of data to another. This helps keep data organized and easy to find.
type EntityA {
id: ID!
name: String!
relatedEntityB: EntityB
}
type EntityB {
id: ID!
description: String!
}Entity references are usually done by including a field that points to another type.
The exclamation mark (!) means the field is required.
type User {
id: ID!
name: String!
orders: [Order]
}
type Order {
id: ID!
total: Float!
}type Post {
id: ID!
title: String!
author: User
}
type User {
id: ID!
username: String!
}This query fetches an author by ID and gets all their posts with titles and content.
type Author {
id: ID!
name: String!
posts: [Post]
}
type Post {
id: ID!
title: String!
content: String!
author: Author
}
query GetAuthorWithPosts {
author(id: "1") {
name
posts {
title
content
}
}
}Entity references help avoid repeating data and keep your schema clean.
Make sure to handle cases where the referenced entity might not exist (null values).
Entity references connect one type to another in GraphQL.
This helps organize data and fetch related information easily.
Use fields that point to other types to create these links.
author: Author.type Author { id: ID! name: String! } type Book { id: ID! title: String! author: Author }{ book { title author { name } } } return if the book's title is "GraphQL Guide" and the author's name is "Alice"?type Book { id: ID! title: String! author: Author }{ book { title author } }author field is an object type, so GraphQL requires specifying which subfields to fetch.author without subfields causes a validation error, as in Because author is an object type and requires subfields.author is an object type and requires subfields -> Option Atype User { id: ID! name: String! posts: [Post!]! } type Post { id: ID! content: String! author: User! }