Accessors & Mutators
10/30/24Less than 1 minute
Accessors & Mutators
Sea-ORM provides ActiveModelBehavior for hooks (before_save/after_save) and derived methods for common access patterns.
ActiveModelBehavior
impl ActiveModelBehavior for ActiveModel {
fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
let mut this = self;
if insert {
// Set creation timestamp on insert
this.created_at = Set(chrono::Utc::now());
}
// Always update the updated_at timestamp
this.updated_at = Set(chrono::Utc::now());
Ok(this)
}
}Derived Accessors
Sea-ORM automatically generates accessor methods for each column, making field access type-safe.
// Accessor methods are available on Model instances
println!("User ID: {}", user.id);
println!("Username: {}", user.username);