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
- Schema-to-Type Mapping
- Type-Safe Query Construction
- Inferring Query Result Shapes
- Relations and Joins with Types