Joins, Loaders & Partial Models
Relevant source files
The following files were used as context for generating this wiki page:
SeaORM 2.0 provides a sophisticated suite of tools for handling relational data efficiently. The system utilizes a "Smart Entity Loader" that automatically selects the most efficient data retrieval strategy—using SQL joins for 1-1 relationships and specialized data loaders for 1-N or M-N relationships to eliminate the N+1 query problem. Partial models complement this by allowing developers to select only a subset of columns, reducing memory overhead and database I/O.
Smart Entity Loader API
The Entity Loader API is the primary entry point for eager loading related entities in SeaORM 2.0. It allows for fluent chaining of relationships and applies different execution strategies based on the nature of the relationship defined in the model.
Execution Strategies
The loader distinguishes between relationship types to optimize performance:
- Joins (1-1): Used for single-valued relationships (e.g.,
HasOne). These are combined into the primary SQL query. - Data Loaders (1-N, M-N): Used for collection relationships (e.g.,
HasMany). These execute separate queries usingINclauses to fetch related data for all primary entities at once.
Loader Methods Summary
| Method | Description | Relationship Type |
|---|---|---|
.load() | Initializes the loader for an Entity. | N/A |
.with(Entity) | Eagerly loads a related entity. | 1-1 (Join) or 1-N (Loader) |
.with((E1, E2)) | Eagerly loads nested relations (e.g., Post and its Tags). | Nested |
.one(db) | Executes query and returns one optional result. | N/A |
.all(db) | Executes query and returns all matching results. | N/A |
Sources: src/lib.rs:164-180, CLAUDE.md:120-135
SQL Joins
SeaORM supports standard relational joins through its query builder. Joins can be used manually or are automatically handled by the loader for 1-1 relationships.
Join Types and Usage
Manual joins allow for traversing relationships through junction tables or performing left joins for optional relations.
Manual Join Example
When performing manual joins, especially with partial models, the join conditions are often inferred from the entity definitions.
let cakes: Vec<CakeWithFruit> = Cake::find()
.left_join(fruit::Entity)
.into_partial_model()
.all(db)
.await?;
Sources: src/lib.rs:281-285
Partial Models
Partial models prevent "overfetching" by defining a specialized struct that only contains the fields required for a specific operation. In SeaORM 2.0, this is achieved using the DerivePartialModel macro.
Features of Partial Models
- Selective Fetching: Only columns present in the partial model struct are included in the generated
SELECTstatement. - Nested Partial Models: A partial model can contain other models or even other partial models as fields, marked with
#[sea_orm(nested)]. - Automatic Projection: Using
.into_partial_model()automatically limits the query's selection to the fields of the target struct.
Sources: src/lib.rs:271-285, CLAUDE.md:137-145
Data Flow for Partial Models
| Step | Component | Action |
|---|---|---|
| 1 | Query Builder | Entity::find() initializes the selection of all columns. |
| 2 | Join (Optional) | .left_join(RelatedEntity) expands the scope to related tables. |
| 3 | Projection | .into_partial_model::<MyStruct>() replaces full selection with fields from MyStruct. |
| 4 | Execution | all(db) executes a query selecting only identified columns. |
Sources: src/lib.rs:271-285, sea-orm-sync/src/lib.rs:271-285
Implementation Details
The core logic for these features is spread across several internal modules that handle query construction and result mapping.
Query Loading Logic
The loading mechanism (found in src/query/loader.rs and src/query/join.rs) manages the complexity of mapping flat database rows into nested object graphs.
- Join Management: Handles the construction of SQL
JOINclauses and alias generation to avoid naming collisions. - Batch Loading: Collects primary keys from the first query and triggers subsequent queries for 1-N relations using batching.
Sources: src/query/loader.rs, src/query/join.rs
Select Extensions
The src/executor/select_ext.rs module provides extension traits that allow queries to be converted into partial models or executed with returning values.
Sources: src/executor/select_ext.rs
Summary of Joins, Loaders & Partial Models
Joins, Loaders, and Partial Models represent the high-efficiency data retrieval layer of SeaORM 2.0. By using the Smart Entity Loader, developers can fetch deeply nested object graphs while the ORM manages the trade-off between SQL joins and separate batch queries. Partial models finalize this efficiency by ensuring that only the necessary bytes are transferred from the database to the application memory.
Sources: src/lib.rs:164-285, sea-orm-sync/src/lib.rs:164-285, CLAUDE.md:120-145