Relations and transactions

Define one-to-many relations

Use the current Drizzle 1.0 defineRelations API to connect users and notes in one type-safe relation map.

8 minute lesson

~~~

Drizzle 1.0 collects relations in one defineRelations() call. Older tutorials use a different API, so check the installed major version before copying them.

Pass the schema object first. Then define both directions: a user has many notes, and each note has one author. The from and to columns make the connection explicit.

import { defineRelations } from 'drizzle-orm'
import * as schema from './schema'

export const relations = defineRelations(schema, r => ({
  users: {
    notes: r.many.notes({
      from: r.users.id,
      to: r.notes.authorId,
    }),
  },
  notes: {
    author: r.one.users({
      from: r.notes.authorId,
      to: r.users.id,
      optional: false,
    }),
  },
}))

optional: false is a type promise that an author always exists. It fits our non-null foreign key. Do not use it to hide nullable or inconsistent data, because the runtime row still decides what exists.

Pass the relations to the Drizzle client according to the current driver documentation. Then the db.query API can include nested records with typed results.

Add the relation map and intentionally swap one from column. Use the TypeScript error or a failing relational test to explain why each direction matters, then restore the correct mapping.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →