Eager Loading
10/30/24Less than 1 minute
Eager Loading
Eager loading helps avoid N+1 query problems by loading related data in a single query.
Basic Eager Loading
use sea_orm::{EntityTrait, RelationTrait};
// Load users with their department info
let users = entity::sys_user::Entity::find()
.find_also_related(entity::sys_dept::Entity)
.all(&db).await?;
// Vec<(sys_user::Model, Option<sys_dept::Model>)>Multiple Relations
let user = entity::sys_user::Entity::find_by_id(1001)
.find_also_related(entity::sys_dept::Entity)
.find_also_related(entity::sys_role::Entity)
.one(&db).await?;Nested Eager Loading
For deeply nested relations, use find_with_related:
let depts = entity::sys_dept::Entity::find()
.find_with_related(entity::sys_user::Entity)
.all(&db).await?;
// Vec<(sys_dept::Model, Vec<sys_user::Model>)>