Soft Deleting
10/30/24Less than 1 minute
Soft Deleting
Soft delete is the recommended approach in QiLuo for data safety and audit trails. Instead of removing records, we mark them with a deleted_at timestamp.
Model Setup
Add a deleted_at: Option<DateTimeUtc> field to your entity:
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "sys_user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
// ... other fields ...
pub deleted_at: Option<DateTimeUtc>,
}Soft Delete Implementation
pub async fn soft_delete(id: i64) -> Result<()> {
let db = DB().await;
let mut record: entity::sys_user::ActiveModel = entity::sys_user::Entity::find_by_id(id)
.one(&db)
.await?
.ok_or_else(|| Error::not_found("Record not found"))?
.into();
record.deleted_at = Set(Some(chrono::Utc::now()));
record.update(&db).await?;
Ok(())
}Query Filters
Always filter out soft-deleted records in list queries:
entity::sys_user::Entity::find()
.filter(entity::sys_user::Column::DeletedAt.is_null())
.all(&db).await?;