Events
10/30/24Less than 1 minute
Events (ActiveModelBehavior)
Sea-ORM provides lifecycle hooks through the ActiveModelBehavior trait, allowing you to execute logic before or after database operations.
Available Hooks
impl ActiveModelBehavior for ActiveModel {
/// Called before saving (insert or update)
fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
where C: ConnectionTrait {
let mut this = self;
if insert {
this.created_at = Set(chrono::Utc::now());
}
this.updated_at = Set(chrono::Utc::now());
Ok(this)
}
/// Called after saving (insert or update)
fn after_save<C>(model: Model, _db: &C, insert: bool) -> Result<Model, DbErr>
where C: ConnectionTrait {
tracing::info!("Model saved: {:?}", model.id);
Ok(model)
}
/// Called before deleting
fn before_delete<C>(self, _db: &C) -> Result<Self, DbErr>
where C: ConnectionTrait {
tracing::warn!("Deleting model");
Ok(self)
}
}Use Cases
- Auto-timestamps: Automatically set
created_atandupdated_at - Audit logging: Log all data modifications
- Validation: Additional business rule validation before save
- Cascade operations: Perform related operations on save/delete