0Pricing
TypeScript Academy · Lesson

Relations and Joins with Types

Model relations so joined results are correctly typed.

Typed Relations and Nested Results

Real schemas have relations: a user has many posts, a post belongs to a user. A type-safe ORM lets you declare these relations and then returns correctly nested, typed results from relational queries.

Declaring Relations

Alongside tables you define a relations object describing how they connect. This metadata powers both the SQL generation and the result type.

import { relations } from "drizzle-orm";

export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, {
    fields: [posts.authorId],
    references: [users.id],
  }),
}));

All lessons in this course

  1. Schema-to-Type Mapping
  2. Type-Safe Query Construction
  3. Inferring Query Result Shapes
  4. Relations and Joins with Types
← Back to TypeScript Academy