Skip to main content
Version: 0.9.x 🚧

Self Referencing

In previous section, we introduced the Linked trait. It can also help you define self referencing relations.

The following example defines an Entity that references itself.

use sea_orm::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "self_join")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub uuid: Uuid,
pub uuid_ref: Option<Uuid>,
pub time: Option<Time>,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(belongs_to = "Entity", from = "Column::UuidRef", to = "Column::Uuid")]
SelfReferencing,
}

pub struct SelfReferencingLink;

impl Linked for SelfReferencingLink {
type FromEntity = Entity;

type ToEntity = Entity;

fn link(&self) -> Vec<RelationDef> {
vec![Relation::SelfReferencing.def()]
}
}