Overview
Drizzle ORM provides a powerful relational query system that allows you to define relationships between tables and fetch related data with type-safe, intuitive syntax.Defining Relations
Relations are defined separately from table schemas using therelations function:
One-to-Many
Define a one-to-many relationship:schema.ts
One-to-One
Define a one-to-one relationship:Many-to-Many
Use a junction table for many-to-many relationships:Composite Foreign Keys
Define relations with composite keys:Relational Queries
Once relations are defined, use the relational query API for intuitive data fetching:Find First
Find a single record:Find Many
Find multiple records:Nested Relations
Fetch deeply nested relationships:Filtering Relations
Filter, order, and limit related records:Selecting Columns
Choose specific columns to return:Extras
Add computed fields to queries:Where Operators
All standard operators are available in relational queries:Order By
Limit and Offset
Self-Referencing Relations
Define hierarchical relationships:Relation Names
Disambiguate multiple relations to the same table:Nullable Relations
Relations automatically handle nullable foreign keys:Best Practices
- Define all relations: Even if you only query from one side, define both sides for completeness
- Use relation names: For multiple relations to the same table, always specify
relationName - Optimize queries: Use
columnsto select only needed fields - Pagination: Always use
limitandoffsetfor large datasets - Filter relations: Filter nested relations to reduce data transfer
Comparison with SQL Joins
- Relational API
- Query Builder
Next Steps
Migrations
Learn how to manage schema changes
Transactions
Execute atomic database operations