sea-orm-relations-kit
The relations SeaORM does not have, with the operations that make them practical.
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. Think Eloquent's polymorphic relations and pivot methods, for
SeaORM.
Features
- Polymorphic relations — one-to-one, one-to-many and many-to-many where the owner can
be one of several entities (
commentable_type+commentable_id); the child resolves its owner into an enum - Pivot operations —
attach,detach,sync,sync_without_detaching,toggle,update_pivot, ordered pivots and extra pivot columns, for polymorphic and plain many-to-many - 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/AVG/MIN/MAXand one row per owner (latest, oldest, cheapest) for anything withRelated<R>, direct or through a junction - Filters — owners that have (or lack) matching related rows, children whose owner matches a query, owners with all given keys
- Any key type —
i32,i64, unsigned, strings, UUIDs (featurewith-uuid); a key is converted to each column's own type - Tested — against SQLite and Postgres, every API doc example compiled
Installation
[]
= "0.1"
Enable with-uuid for UUID primary keys.
Polymorphic one-to-many
Name each owner entity, and declare the child's two columns once:
use ;
pub const COMMENTABLE: =
new;
The stored type is a short alias, not a type name: renaming the entity breaks nothing.
From the owner:
let mut comment = ActiveModel ;
COMMENTABLE.associate?; // sets both columns
comment.insert.await?;
let comments = COMMENTABLE.find_for?.all.await?; // a query: filter, order, paginate
let per_post = COMMENTABLE.load_for.await?; // Vec<Vec<comment>> in one query
let counts = COMMENTABLE.count_for.await?; // [3, 0, 1]
let latest = COMMENTABLE.latest_for.await?;
From the child, the owner comes back as an enum of the possible owners:
morph_target!
let owner: = COMMENTABLE.owner.await?;
let owners: = COMMENTABLE.load_owners.await?; // one query per type
A stored type the enum does not cover is an error, not a silent None.
Many-to-many: pivot operations
use ;
// posts and videos <-> tags, through taggables (tag_id, taggable_type, taggable_id, position)
pub const TAGS: = new
.ordered_by;
// users <-> roles, through role_user (user_id, role_id)
pub const ROLES: =
new;
TAGS.attach.await?; // skips ones already attached
let changes = TAGS.sync.await?; // exactly these, in this order
// changes.attached, changes.detached, changes.updated (moved)
TAGS.toggle.await?;
TAGS.detach.await?;
ROLES.attach_with.await?;
ROLES.update_pivot.await?;
let tags = TAGS.find_for?.all.await?; // in pivot order
let per_post = TAGS.load_for.await?; // two queries for the whole page
let posts_of_tag = TAGS.?.all.await?;
SeaORM's own relations
For anything with a Related<R> impl, has_many or many-to-many through a junction:
use ;
let comments = .await?; // [3, 0, 1]
let revenue = .await?;
let last_order = .await?;
Ties in one-of-many go to the row with the largest key (smallest for oldest_of_many).
Filters
Conditions for any query, so they combine with everything else:
// posts with at least one approved comment
find.filter;
// comments left on published posts
find.filter;
// posts tagged with both
find.filter;
Cleaning up
A polymorphic column cannot have a foreign key, so the database cannot cascade. Call
COMMENTABLE.delete_for(db, &post) / TAGS.detach_all(db, &post) in the owner's delete hook,
or delete_orphans::<posts::Entity, _>(db) from a scheduled task.
Migrations
use ;
let = morph_columns;
// ... .col(type_column).col(id_column) in Table::create()
manager.create_index.await?;
Give the *_id column the same type as the owners' keys: the filters compare the two
columns directly.
Good to know
- Batch methods put the owners' keys in one
IN (...)list: pass a page, not a table. - Writes that take several statements (
sync,toggle) are not atomic on their own; pass a transaction asdbwhen that matters. - Pivot rows are written in bulk, so the pivot entity's own hooks do not run.
Coming from Laravel
| Eloquent | sea-orm-relations-kit |
|---|---|
Relation::enforceMorphMap([...]) |
impl Morphable { const MORPH_TYPE } |
morphMany / morphOne |
Morph::find_for(&owner) (+ .one(db)) |
morphTo |
Morph::owner with a morph_target! enum |
associate / dissociate |
Morph::associate / dissociate |
morphToMany / belongsToMany |
MorphToMany / BelongsToMany |
morphedByMany |
MorphToMany::owners_of::<O>(&tag) |
attach, detach, sync, toggle |
same names |
syncWithoutDetaching, syncWithPivotValues |
sync_without_detaching, sync_with |
updateExistingPivot |
update_pivot |
with('comments') |
load_for(db, &posts) |
with('commentable') |
load_owners(db, &comments) |
withCount, withExists |
count_for, count_related, exists_related |
withSum / withAvg / withMin / withMax |
aggregate_for, aggregate_related |
latestOfMany / oldestOfMany / ofMany |
latest_for / oldest_for / pick_for, latest_of_many, ... |
whereHas / whereDoesntHave |
owners_with / owners_without |
whereHasMorph / whereDoesntHaveMorph |
owned_by / not_owned_by |
whereMorphedTo |
Morph::of(&owner) |
$table->morphs('commentable') |
schema::morph_columns + morph_index |
Contributing
Issues and pull requests are welcome. The tests run on in-memory SQLite; for Postgres set
RELATIONS_KIT_DATABASE_URL:
RELATIONS_KIT_DATABASE_URL=postgres://...
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.