0
0
GraphQLquery~5 mins

One-to-one relationships in GraphQL

Choose your learning style9 modes available
Introduction

One-to-one relationships connect two pieces of data so each item matches exactly one item in the other set. This helps keep data organized and easy to find.

When each user has exactly one profile with extra details.
When each product has one unique warranty record.
When each employee has one personal locker assigned.
When each car in a system has one registration document.
Syntax
GraphQL
type User {
  id: ID!
  name: String!
  profile: Profile!
}

type Profile {
  id: ID!
  bio: String
  user: User!
}

Use a field in one type to link to the other type.

Mark the linked field as non-null if it must always exist.

Examples
This example shows a person linked to exactly one passport, and vice versa.
GraphQL
type Person {
  id: ID!
  name: String!
  passport: Passport!
}

type Passport {
  id: ID!
  number: String!
  person: Person!
}
Each employee has one locker, and each locker belongs to one employee.
GraphQL
type Employee {
  id: ID!
  name: String!
  locker: Locker!
}

type Locker {
  id: ID!
  location: String!
  employee: Employee!
}
Sample Program

This query fetches a user and their linked profile using a one-to-one relationship.

GraphQL
type User {
  id: ID!
  name: String!
  profile: Profile!
}

type Profile {
  id: ID!
  bio: String
  user: User!
}

query GetUserWithProfile {
  user(id: "1") {
    id
    name
    profile {
      id
      bio
    }
  }
}
OutputSuccess
Important Notes

One-to-one links help avoid repeating data in multiple places.

Make sure to keep the link consistent on both sides to avoid confusion.

Summary

One-to-one relationships connect exactly one item to one other item.

They keep data neat and easy to access.

Use linked fields in GraphQL types to represent these connections.