SeaORM Relations Kit
The relations SeaORM does not have: polymorphic one-to-many and many-to-many, attach/sync/toggle on pivots, counts, aggregates and latest-of-many for whole pages without N+1 queries.
Comments on posts and videos, one tags table for every entity, attach / sync /
toggle on a pivot, "how many comments has each post", "the latest comment of each post":
all without N+1 queries, for SeaORM, the ORM behind Loco.
Features
- Polymorphic relations: one-to-one, one-to-many and many-to-many where the owner can be one of several entities; a child resolves its owner into an enum
- Pivot operations:
attach,detach,sync,sync_without_detaching,toggle,update_pivot, ordered pivots and extra pivot columns, polymorphic and plain - Eager loading and counts: the children, related rows or owners of a whole page in one or two queries
- For SeaORM's own relations: counts, exists, sum / average / min / max and one row per
owner for anything with
Related<R>, direct or through a junction - Filters: owners that have or lack matching related rows, children whose owner matches a query
- Any key type:
i32,i64, strings, UUIDs - Tested on SQLite and Postgres
Installation
cargo add sea-orm-relations-kit
Polymorphic one-to-many
use sea_orm_relations_kit::{Morph, Morphable};
impl Morphable for posts::Entity {
const MORPH_TYPE: &'static str = "post";
}
pub const COMMENTABLE: Morph<comments::Entity> =
Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
let comments = COMMENTABLE.find_for(&post)?.all(db).await?;
let per_post = COMMENTABLE.load_for(db, &posts).await?; // one query for the page
let counts = COMMENTABLE.count_for(db, &posts).await?; // [3, 0, 1]
The owner of a comment comes back as an enum:
sea_orm_relations_kit::morph_target! {
pub enum Commentable {
Post(posts::Entity),
Video(videos::Entity),
}
}
let owner: Option<Commentable> = COMMENTABLE.owner(db, &comment).await?;
Many-to-many
TAGS.attach(db, &post, [rust.id, loco.id]).await?;
let changes = TAGS.sync(db, &post, [loco.id, sea.id]).await?; // attached, detached, moved
TAGS.toggle(db, &post, [rust.id]).await?;
let per_post = TAGS.load_for(db, &posts).await?;