ORM — Queries
objects, filter, paginate, relations, create/update/delete.
● ● ●
let db = &request.engine.db;
// All records
let articles = article::Entity::find()
.all(db).await.unwrap_or_default();
// With filter
let article = article::Entity::find()
.filter(article::Column::Slug.eq("my-article"))
.one(db).await.unwrap_or(None);
// By primary key
let article = article::Entity::find_by_id(42)
.one(db).await.unwrap_or(None);
// Sort + limit
let recent = article::Entity::find()
.order_by_desc(article::Column::CreatedAt)
.limit(10)
.all(db).await.unwrap_or_default();
// In entities/article.rs
model! { Article, ... }
impl_objects!(Entity); // Enables the objects manager
// In views.rs
let db = &request.engine.db;
let all = Article::objects.all().all(db).await?;
let active = Article::objects.filter(Column::Published.eq(true)).all(db).await?;
let count = Article::objects.count(db).await?;
let found = Article::objects.get(db, 42).await?; // Err if missing
let opt = Article::objects.get_optional(db, 99).await?; // None if missing
// 404 page if missing: returns Result<Model, Response>
let article = match Article::objects.get_or_404(db, id, &request, "Not found").await {
Ok(article) => article,
Err(not_found) => return Ok(not_found),
};
use sea_orm::ActiveValue::Set;
use crate::entities::article::ActiveModel;
let db = &request.engine.db;
// Create
let new_article = ActiveModel {
title: Set("My article".to_string()),
content: Set("Content...".to_string()),
published: Set(false),
..Default::default()
};
let saved = new_article.insert(db).await?;
// Update
let mut article: ActiveModel = saved.into();
article.title = Set("New title".to_string());
article.update(db).await?;
// Delete
article::Entity::delete_by_id(42).exec(db).await?;