Inserting & Updating Models
10/30/24Less than 1 minute
Inserting & Updating Models
Insert
Use ActiveModel with Set to create new records:
use sea_orm::{ActiveModelTrait, Set};
let user = entity::sys_user::ActiveModel {
username: Set("alice".to_owned()),
password_hash: Set(hash_password("secret")),
status: Set(1),
created_at: Set(chrono::Utc::now()),
..Default::default()
};
let result = user.insert(&db).await?;Update
Load an existing record and update fields:
let mut user: entity::sys_user::ActiveModel = entity::sys_user::Entity::find_by_id(1001)
.one(&db)
.await?
.ok_or_else(|| anyhow::anyhow!("not found"))?
.into();
user.username = Set("bob".to_owned());
user.updated_at = Set(chrono::Utc::now());
let updated = user.update(&db).await?;Bulk Update
use sea_orm::{EntityTrait, QueryFilter, ColumnTrait};
entity::sys_user::Entity::update_many()
.col_expr(entity::sys_user::Column::Status, Expr::value(0))
.filter(entity::sys_user::Column::DeptId.eq(10))
.exec(&db).await?;