ORM — Queries
objects, filter, paginate, relations, create/update/delete.
● ● ●
let db = request.engine.db.clone();
// 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 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
let or_404 = Article::objects.get_or_404(&db, id, &request, "Not found").await?;
use sea_orm::ActiveValue::Set;
use crate::entities::article::ActiveModel;
// 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 = found.into();
article.title = Set("New title".to_string());
article.update(&*db).await?;
// Delete
article::Entity::delete_by_id(42).exec(&*db).await?;