Relations

Grafbase automatically generates the applicable types, connections, and input types for relations between models depending on what you configure inside your schema.

Grafbase supports the following relationship types:

  • One to One
  • One to Many / Many to One
  • Many to Many

The example below shows the One to One relation between User and Profile.

A User has one Profile, and Profile has one User.

type User @model {
  name: String
  profile: Profile
}

type Profile @model {
  bio: String
  user: User
}

The example below shows the One to Many relation between Category and Post.

A Category has many Posts.

type Category @model {
  name: String
  posts: [Post]
}

type Post @model {
  title: String
  category: Category
}

The example below shows the Many to Many relation between Category and Posts.

A Post has many Category entries, and each Category has many Posts.

type Category @model {
  name: String
  posts: [Post]
}

type Post @model {
  title: String
  category: [Category]
}

Grafbase automatically generates input types for mutations to link and unlink models.

Grafbase automatically generates mutations for creating entries for child nodes at the time of creating the parent.

mutation {
  postCreate(
    input: {
      title: "Hello Grafbase"
      category: { create: { name: "Announcements" } }
    }
  ) {
    post {
      title
      category {
        name
      }
    }
  }
}

Learn more about nested mutations.

Grafbase supports the ability to define relations as non-nullable.

In the example below we have a Post model that must have a non-nullable type Category, as well as a Category with non-nullable list Posts.

type Category @model {
  name: String
  posts: [Post!]!
}

type Post @model {
  title: String
  category: Category!
}

Learn more about non-nullable lists.

You can provide a custom name for relations when referencing the same model more than once using the @relation directive:

type Order @model {
  billingAddress: Address @relation(name: "billing")
  shippingAddress: Address @relation(name: "shipping")
}

type Address @model {
  line1: String!
  line2: String
  zip: String
  phone: PhoneNumber
}
Was this page helpful?