恒美微站 Logo 恒美微站
  • 首页
  • 关于我们
  • 建站服务
  • 主题模板
  • 案例展示
  • 资讯中心
  • 联系我们

Sea-ORM 的增删改查

  • 首页
  • 资讯中心
  • /
  • Sea-ORM 的增删改查

相关资讯

基于RAG的物流包装规范问答系统设计毕设源码(源码+lw+部署文档+讲解等) 2026/9/29 15:09:35
基于RAG的物流冷链运输咨询系统设计计算机毕设(源码+lw+部署文档+讲解等) 2026/9/29 15:09:35
一文打通AI网关:Windows环境下OpenClaw安装与主流大模型配置全攻略(TaoToken统一Key接入版) 2026/9/29 15:09:35

最新资讯

OpenClaw接入CapSolver:AI Agent验证码自动识别实战指南
工业交换机bypass光旁路保护:原理、选型与现场排障指南
银河麒麟V10上编译e1000e与rtl8125网卡驱动:从环境检查到避坑
C#实现OPC UA客户端实时采集PLC数据写入SQL Server的完整方案
手机屏幕缺陷检测数据集与YOLO11训练实战:1000张图三种标签格式一键跑通
Spring Boot秋季节气网站实战:从零构建完整Web全栈项目

今日推荐

开源模型端侧落地实战:量化、推理加速与Agent上下文管理
AI Evals实战指南:从零搭建LLM应用评估体系与CI/CD集成
Java采购管理系统实战:从数据库设计到事务一致性

本周热门

从像素到笔画:srt-whiteboard-animation骨架笔迹追踪实现(Zhang-Suen细化+8邻接追踪)
网站建设的英语怎么说?别只背单词,看完这套安全完整流程才敢上线
新手入门看这篇:建设网站加盟避坑指南与SEO实操

本月精选

自研推理加速器Redwood:两周内实现PyTorch模型高效部署的实战教程
V4L2摄像头采集实战:从camera_client.rar到出图全流程解析
从“谁发明了钢琴键”到知识问答智能体:RAG与记忆工程实践

Sea-ORM 的增删改查

发布时间:2026/9/29 15:09:35
Sea-ORM 的增删改查 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和事务使用吗

关于恒美微站

恒美微站专注于为个体商户、工作室提供极简自助建站服务,让每个人都能轻松拥有专业网站。

快速链接

  • 关于我们
  • 建站服务
  • 主题模板
  • 案例展示
  • 资讯中心

服务项目

  • 可视化建站
  • 拖拽编辑
  • 主题定制
  • SEO 优化
  • 网站托管

联系方式

  • 📍 地址:北京市朝阳区建国路 88 号
  • 📞 电话:400-888-8888
  • ✉️ 邮箱:info@hmyw.cn
  • 🕐 时间:周一至周日 9:00-18:00

© 2024 恒美微站 hmyw.cn 版权所有 | 京 ICP 备 12345678 号