0
0
GraphqlHow-ToBeginner · 4 min read

How to Define Relationships in GraphQL: Syntax and Examples

In GraphQL, you define relationships by adding fields in your types that reference other types, often as objects or lists. Use type definitions with fields pointing to related types, and implement resolvers to fetch related data.
📐

Syntax

To define a relationship in GraphQL, add a field in one type that references another type. Use the related type's name as the field's type. For one-to-many relationships, use a list indicated by square brackets [].

Example parts:

  • type User: defines a user object.
  • posts: [Post]: a field in User that links to many Post objects.
  • type Post: defines a post object.
graphql
type User {
  id: ID!
  name: String!
  posts: [Post]
}

type Post {
  id: ID!
  title: String!
  author: User
}
💻

Example

This example shows a simple GraphQL schema with User and Post types. Each user can have many posts, and each post has one author. The resolver functions fetch related data to complete the relationship.

javascript
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    posts: [Post]
  }

  type Post {
    id: ID!
    title: String!
    author: User
  }

  type Query {
    users: [User]
    posts: [Post]
  }
`;

const users = [
  { id: '1', name: 'Alice' },
  { id: '2', name: 'Bob' }
];

const posts = [
  { id: 'a', title: 'Hello World', authorId: '1' },
  { id: 'b', title: 'GraphQL Rocks', authorId: '1' },
  { id: 'c', title: 'Goodbye', authorId: '2' }
];

const resolvers = {
  Query: {
    users: () => users,
    posts: () => posts
  },
  User: {
    posts: (user) => posts.filter(post => post.authorId === user.id)
  },
  Post: {
    author: (post) => users.find(user => user.id === post.authorId)
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

Common mistakes when defining relationships in GraphQL include:

  • Not matching field names and resolver keys exactly.
  • Forgetting to implement resolvers for relationship fields, causing null results.
  • Using incorrect types (e.g., missing list brackets for multiple related items).
  • Creating circular references without proper resolver handling.

Always ensure your schema types and resolvers align.

javascript
/* Wrong: Missing resolver for posts field in User type */
const resolversWrong = {
  Query: {
    users: () => users
  }
};

/* Right: Add resolver to fetch posts for each user */
const resolversRight = {
  Query: {
    users: () => users
  },
  User: {
    posts: (user) => posts.filter(post => post.authorId === user.id)
  }
};
📊

Quick Reference

ConceptDescriptionExample
One-to-OneField references a single related typeauthor: User
One-to-ManyField references a list of related typesposts: [Post]
ResolverFunction to fetch related dataUser.posts = (user) => posts.filter(...)
Type DefinitionDefines object shape and relationshipstype User { posts: [Post] }

Key Takeaways

Define relationships by adding fields in types that reference other types or lists of types.
Implement resolvers for relationship fields to fetch related data correctly.
Use square brackets [] in type definitions for one-to-many relationships.
Ensure field names in schema and resolvers match exactly to avoid null results.
Test relationships with queries to confirm data resolves as expected.