
Sea-ORM 的增删改查主要围绕这几个概念Entity对应数据库表Model查询出来的完整记录ActiveModel用于插入、更新的数据载体ActiveValue::Set/NotSet控制哪些字段参与 SQL下面以users表为例。1. 定义实体use sea_orm::entity::prelude::*; #[derive(Clone, Debug, PartialEq, DeriveEntityModel)] #[sea_orm(table_name users)] pub struct Model { #[sea_orm(primary_key)] pub id: i32, pub name: String, pub email: String, } #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] pub enum Relation {} impl ActiveModelBehavior for ActiveModel {}假设这个模块叫user后面用user::Entity、user::Model、user::ActiveModel来操作。2. 增Create插入单条use sea_orm::ActiveValue::Set; let new_user user::ActiveModel { name: Set(张三.to_owned()), email: Set(zhangsanexample.com.to_owned()), ..Default::default() }; let result user::Entity::insert(new_user).exec(db).await?; // 如果是自增主键这里可以拿到插入后的 id let inserted_id result.last_insert_id;批量插入let users vec![ user::ActiveModel { name: Set(张三.to_owned()), email: Set(zhangsanexample.com.to_owned()), ..Default::default() }, user::ActiveModel { name: Set(李四.to_owned()), email: Set(lisiexample.com.to_owned()), ..Default::default() }, ]; user::Entity::insert_many(users).exec(db).await?;3. 查Read查询全部let users: Vecuser::Model user::Entity::find().all(db).await?;按主键查询let user: Optionuser::Model user::Entity::find_by_id(1).one(db).await?;条件查询let users user::Entity::find() .filter(user::Column::Name.eq(张三)) .all(db) .await?;模糊查询let users user::Entity::find() .filter(user::Column::Name.contains(张)) .all(db) .await?;分页查询let paginator user::Entity::find().paginate(db, 10); // 第 0 页 let page paginator.fetch_page(0).await?;4. 改Update更新单条记录的部分字段use sea_orm::ActiveValue::Set; let u user::Entity::find_by_id(1) .one(db) .await? .expect(user not found); // Model 转成 ActiveModel let mut active: user::ActiveModel u.into(); // 只修改 name active.name Set(李四.to_owned()); let updated active.update(db).await?;关键点只有被设置为Set(...)的字段才会进入UPDATE ... SET没有Set的字段不会更新批量条件更新use sea_orm::sea_query::Expr; user::Entity::update_many() .col_expr(user::Column::Email, Expr::value(newexample.com)) .filter(user::Column::Name.eq(张三)) .exec(db) .await?;也可以用set()let partial user::ActiveModel { email: Set(newexample.com.to_owned()), ..Default::default() }; user::Entity::update_many() .set(partial) .filter(user::Column::Id.eq(1)) .exec(db) .await?;5. 删Delete删除单条记录let u user::Entity::find_by_id(1) .one(db) .await? .expect(user not found); u.delete(db).await?;按条件批量删除user::Entity::delete_many() .filter(user::Column::Name.eq(张三)) .exec(db) .await?;按主键删除user::Entity::delete_by_id(1).exec(db).await?;6. 完整 CRUD 示例use sea_orm::*; use sea_orm::ActiveValue::Set; pub async fn create_user( db: DatabaseConnection, name: str, email: str, ) - Resulti32, DbErr { let model user::ActiveModel { name: Set(name.to_owned()), email: Set(email.to_owned()), ..Default::default() }; let res user::Entity::insert(model).exec(db).await?; Ok(res.last_insert_id) } pub async fn get_user( db: DatabaseConnection, id: i32, ) - ResultOptionuser::Model, DbErr { user::Entity::find_by_id(id).one(db).await } pub async fn update_user_name( db: DatabaseConnection, id: i32, new_name: str, ) - Resultuser::Model, DbErr { let u user::Entity::find_by_id(id) .one(db) .await? .ok_or(DbErr::RecordNotFound(user not found.to_owned()))?; let mut active: user::ActiveModel u.into(); active.name Set(new_name.to_owned()); active.update(db).await } pub async fn delete_user( db: DatabaseConnection, id: i32, ) - ResultDeleteResult, DbErr { user::Entity::delete_by_id(id).exec(db).await }常见注意点插入和更新都用ActiveModel插入构造ActiveModel更新通常先查出Model再转成ActiveModel只有Set的字段才会参与更新active.name Set(新名字.to_owned());批量操作优先用insert_many/update_many/delete_many不要循环单条操作性能会差很多。查询结果可能是OptionModelfind_by_id(...).one(db)返回的是Option生产代码里建议显式处理不要随便unwrap()。如果涉及多步操作建议用事务let txn db.begin().await?; // 在事务里执行增删改查 user::Entity::insert(model).exec(txn).await?; txn.commit().await?;需要我接着讲讲 Sea-ORM 的关联查询JOIN和事务使用吗