<p align="center">
<img src="https://raw.githubusercontent.com/axvilab/sea-orm-relations-kit/main/assets/logo.png" alt="sea-orm-relations-kit logo" width="128" height="128">
</p>
# sea-orm-relations-kit
**The relations [SeaORM](https://www.sea-ql.org/SeaORM/) does not have, with the operations that make them practical.**
[](https://crates.io/crates/sea-orm-relations-kit)
[](https://docs.rs/sea-orm-relations-kit)
[](https://github.com/axvilab/sea-orm-relations-kit/actions/workflows/ci.yml)
[](#license)
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` / `MAX` and one row
per owner (latest, oldest, cheapest) 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, owners with all given keys
- **Any key type** — `i32`, `i64`, unsigned, strings, UUIDs (feature `with-uuid`); a key is
converted to each column's own type
- **Tested** — against SQLite and Postgres, every API doc example compiled
## Installation
```toml
[dependencies]
sea-orm-relations-kit = "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:
```rust
use sea_orm_relations_kit::{Morph, Morphable};
impl Morphable for posts::Entity {
const MORPH_TYPE: &'static str = "post";
}
impl Morphable for videos::Entity {
const MORPH_TYPE: &'static str = "video";
}
pub const COMMENTABLE: Morph<comments::Entity> =
Morph::new(comments::Column::CommentableType, comments::Column::CommentableId);
```
The stored type is a short alias, not a type name: renaming the entity breaks nothing.
From the owner:
```rust
let mut comment = comments::ActiveModel { body: Set("Nice".into()), ..Default::default() };
COMMENTABLE.associate(&mut comment, &post)?; // sets both columns
comment.insert(db).await?;
let comments = COMMENTABLE.find_for(&post)?.all(db).await?; // a query: filter, order, paginate
let per_post = COMMENTABLE.load_for(db, &posts).await?; // Vec<Vec<comment>> in one query
let counts = COMMENTABLE.count_for(db, &posts).await?; // [3, 0, 1]
let latest = COMMENTABLE.latest_for(db, &posts, comments::Column::CreatedAt).await?;
```
From the child, the owner comes back as an enum of the possible owners:
```rust
sea_orm_relations_kit::morph_target! {
#[derive(Clone, Debug)]
pub enum Commentable {
Post(posts::Entity),
Video(videos::Entity),
}
}
let owner: Option<Commentable> = COMMENTABLE.owner(db, &comment).await?;
let owners: Vec<Option<Commentable>> = COMMENTABLE.load_owners(db, &comments).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
```rust
use sea_orm_relations_kit::{BelongsToMany, Morph, MorphToMany};
// posts and videos <-> tags, through taggables (tag_id, taggable_type, taggable_id, position)
pub const TAGS: MorphToMany<taggables::Entity, tags::Entity> = MorphToMany::new(
Morph::new(taggables::Column::TaggableType, taggables::Column::TaggableId),
taggables::Column::TagId,
)
.ordered_by(taggables::Column::Position);
// users <-> roles, through role_user (user_id, role_id)
pub const ROLES: BelongsToMany<role_user::Entity, roles::Entity> =
BelongsToMany::new(role_user::Column::UserId, role_user::Column::RoleId);
```
```rust
TAGS.attach(db, &post, [rust.id, loco.id]).await?; // skips ones already attached
let changes = TAGS.sync(db, &post, [loco.id, sea.id]).await?; // exactly these, in this order
// changes.attached, changes.detached, changes.updated (moved)
TAGS.toggle(db, &post, [rust.id]).await?;
TAGS.detach(db, &post, [sea.id]).await?;
ROLES.attach_with(db, &user, [admin.id], |pivot| {
pivot.note = Set(Some("on call".into()));
Ok(())
}).await?;
ROLES.update_pivot(db, &user, admin.id, |update| {
update.col_expr(role_user::Column::Note, Expr::value("lead"))
}).await?;
let tags = TAGS.find_for(&post)?.all(db).await?; // in pivot order
let per_post = TAGS.load_for(db, &posts).await?; // two queries for the whole page
let posts_of_tag = TAGS.owners_of::<posts::Entity>(&rust)?.all(db).await?;
```
## SeaORM's own relations
For anything with a `Related<R>` impl, `has_many` or many-to-many through a junction:
```rust
use sea_orm_relations_kit::{aggregate_related, count_related, latest_of_many, Aggregate};
let comments = count_related::<comments::Entity, _, _>(db, &posts).await?; // [3, 0, 1]
let revenue = aggregate_related::<orders::Entity, _, _>(db, &customers, orders::Column::Total, Aggregate::Sum).await?;
let last_order = latest_of_many::<orders::Entity, _, _>(db, &customers, orders::Column::CreatedAt).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:
```rust
// posts with at least one approved comment
posts::Entity::find().filter(COMMENTABLE.owners_with::<posts::Entity>(
comments::Entity::find().filter(comments::Column::Approved.eq(true)),
));
// comments left on published posts
comments::Entity::find().filter(COMMENTABLE.owned_by(
posts::Entity::find().filter(posts::Column::Published.eq(true)),
));
// posts tagged with both
posts::Entity::find().filter(TAGS.owners_with_all::<posts::Entity>([rust.id, loco.id])?);
```
## 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
```rust
use sea_orm_relations_kit::schema::{morph_columns, morph_index, KeyType};
let [type_column, id_column] = morph_columns("commentable", KeyType::BigInteger);
// ... .col(type_column).col(id_column) in Table::create()
manager.create_index(morph_index("comments", "commentable")).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 as `db` when that matters.
- Pivot rows are written in bulk, so the pivot entity's own hooks do not run.
## Coming from Laravel
| `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`:
```sh
cargo test --all-features
RELATIONS_KIT_DATABASE_URL=postgres://... cargo test --all-features --tests -- --test-threads=1
```
## License
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) 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.
---
Made by [AxVi](https://axvi.dev) · part of [AxViLab](https://github.com/axvilab)