Relationships
10/30/24Less than 1 minute
Relationships
Sea-ORM supports three types of relationships: BelongsTo, HasMany, and HasOne.
Defining Relationships
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
// Belongs To (many-to-one)
#[sea_orm(
belongs_to = "super::sys_dept::Entity",
from = "Column::DeptId",
to = "super::sys_dept::Column::Id"
)]
Dept,
// Has Many (one-to-many)
#[sea_orm(
has_many = "super::sys_login_log::Entity",
from = "Column::Id",
to = "super::sys_login_log::Column::UserId"
)]
LoginLogs,
}Querying with Relations
use sea_orm::{EntityTrait, RelationTrait};
// Find user with their department
let user = entity::sys_user::Entity::find_by_id(1001)
.find_also_related(entity::sys_dept::Entity)
.one(&db).await?;
// Result: Option<(Model, Option<sys_dept::Model>)>