Allow packages to define their own relation types
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
Research direction
Start with macros/model/src/relation.rs and macros/model/src/model.rs to see how relation attributes are recognized and exposed, then read crates/database/src/model/relation.rs and crates/database/src/model/loaded.rs for the relation contract and loading behavior. The issue recommends a public CustomRelation trait and an adapter to AnyRelation, plus a #[relation(custom = ..)] attribute. Done means custom relations integrate with eager loading, nested loading, has, and with_count, with the proposed JSON relation cases covered by tests on SQLite, PostgreSQL, and MySQL.
Written by the indexing model from the issue text.
Description
The problem
Eloquent lets a package add a relation type by extending Illuminate\Database\Eloquent\Relations\Relation
(addConstraints, addEagerConstraints, initRelation, match, getResults, getRelationExistenceQuery).
Once a relation method returns that object, with, load, has, whereHas, withCount and serialization all
work with it. Several widely used packages are built on this:
staudenmeir/eloquent-json-relations:
BelongsToJson/HasManyJson, relations through arrays of keys inside JSON columns
($this->belongsToJson(Role::class, 'options->role_ids')).staudenmeir/eloquent-has-many-deep: relations
through any number of intermediate models.staudenmeir/laravel-adjacency-list:ancestors,
descendantsand other recursive relations.
In Laravel for Rust, a relation is a field with one of eleven attributes, and there is no public way to add
another kind. Everything a relation needs exists, but it's all #[doc(hidden)]. References are to 0.x at
3693a2dc:
#[model]recognizes a fixed list of attributes: theKindenum andKind::ALLin
macros/model/src/relation.rsL58–87,
matched inKind::of/Kind::of_attr(L89–99).with,hasandwith_countfind a relation throughModel::__relation(TypeId)
(crates/database/src/model/mod.rsL125–130),
which only#[model]generates
(macros/model/src/model.rsL372–381).
Any other function from&Mto a query is accepted by theRelationtrait but panics inrelation_of
(crates/database/src/model/relation.rsL121, L205–225).- The relation contract itself,
AnyRelation(load,exists,count,aggregate,load_missing,
query…), is hidden
(relation.rsL1146–1147),
and so areDefinition(L1539–1540, built on the privateKindat L1271), theSlottrait that relation field
types implement to receive eager-loaded models
(crates/database/src/model/loaded.rsL19–22),
and their re-exports (mod.rsL79–85).
What this means for a package
We're porting eloquent-json-relations to Laravel for Rust. The best we can do today is make relations values
instead of fields, and give them their own methods built on the query builder:
impl User {
pub const ROLES: BelongsToJson<User, Json<Value>, Role, i64> =
BelongsToJson::new(User::options, "role_ids", Role::id);
}
let users = User::query().get().await?;
let roles: Vec<Vec<Role>> = User::ROLES.load(&users).await?; // instead of .with(User::roles)
let admins = User::query()
.filter(User::ROLES.exists_where(Role::name.eq("admin")).await?) // instead of .has_where(..)
.get()
.await?;
That works, but:
with,has,has_where,with_count,load_missingand nested eager loads (Post::comments.with(..))
don't accept these relations, so every application call site differs from a built-in relation.- Loaded models aren't in a field, so they aren't serialized with the parent and can't be nested.
- Anything built on
Relation<M> + IntoEager<M>can't use them. For example, a JSON:API layer can't expose
them as relationships or?include=them. - The package needs hidden APIs anyway:
laravel::model::__query::<M>()(theModeltrait has no generic
query()) andColumn::get.
The same applies to has-many-deep, adjacency lists, and any application-specific relation.
Alternatives
A. Make AnyRelation and Slot public and stable
Document AnyRelation, Slot and the types in their signatures, and add an attribute such as
#[relation(definition = PATH)] that puts a user-provided &'static dyn AnyRelation<Self, N> into
Model::__relation.
- Pros: full parity with built-in relations: eager loading,
has,with_count, aggregates,load_missing,
and with a JSON:API layer, serialization and includes all work. Little macro work. - Cons: the largest public surface.
AnyRelationexposesAggregate,Inverse,JoinTable,SetParent,
Location,join_parentfor through relations, and the&mut [&mut P]loading protocol. These internals
become semver-bound, which limits refactoring during 0.x. Implementing it correctly is hard: it has to fill
Slots, respectCHUNK, and handleOfMany. - Possible mitigation: seal the methods that only built-in kinds need (
join_parent,parent_setter,
inverse,join_table), with default implementations that refuse the operation.
B. A smaller public extension trait, adapted internally (recommended)
Add a public trait for what a custom relation actually decides, and let the framework adapt it to AnyRelation
with the existing loading, chunking, Slot filling and aggregate code. A sketch:
pub trait CustomRelation<P: Model, N: Model>: Send + Sync + 'static {
type Key: Clone + Eq + Hash + IntoExpr + Send + Sync;
/// The keys a parent refers to; an empty list means no related rows.
fn parent_keys(&self, parent: &P) -> Vec<Self::Key>;
/// The related rows of these keys, in one query (the framework chunks the keys).
fn eager_query(&self, keys: &[Self::Key]) -> Builder<N>;
/// The keys a related row answers to, to match it back to its parents.
fn related_keys(&self, related: &N) -> Vec<Self::Key>;
/// The correlated condition for `has`/`with_count`, or `None` if the relation can't be filtered in SQL.
fn existence(&self, related: Builder<N>) -> Option<Condition> { None }
}
The #[model] field would reuse the existing field types, and the attribute would name the definition:
#[model]
pub struct User {
pub id: i64,
pub options: Json<UserOptions>,
#[relation(custom = roles_through_options)]
pub roles: BelongsToMany<Role>, // or HasMany / BelongsTo / HasOne
}
- Pros: a small, key-based surface that's easy to keep stable, since the framework keeps ownership of the loading
protocol andSlot.with, nested eager loads, serialization,try_loadedand anything built on
Relation<M> + IntoEager<M>, such as JSON:API includes, work unchanged. It covers JSON relations,
has-many-deep and adjacency lists with eager loading. - Cons: new macro work for one attribute and a generic adapter in
relation.rs. Write-side helpers (create
through the relation,sync) stay unsupported for custom relations, which is fine for a first step.has
needsexistence, and for JSON relations that needs a correlated JSON containment. TodayExpr::json_contains
only takes a bound value, so a column operand, as in Eloquent'swhereJsonContainswith a column on PostgreSQL
and MySQL, would be a useful companion.
C. Add the missing relation kinds to the framework itself
Teach the existing attributes JSON paths and add a JSON kind, for example
#[belongs_to(foreign_key = "options->user_id")] and #[belongs_to_json(path = "options->role_ids")].
- Pros: no new extension API to stabilize, and the best ergonomics for these specific cases.
- Cons: it doesn't scale. Every package's semantics, such as deep relations or recursive CTEs, would have to
live in the framework. It doesn't help application-specific relations.
D. Keep the current design and document the pattern
Document "relations as values" (a struct with load/exists built on the query builder) as the supported way
for packages, and expose a generic Model::query() so they don't need __query.
- Pros: no new public API and no semver risk.
- Cons: none of the integration listed above. Packages stay second-class, and their users write different
code for each relation kind.
Recommendation
B. It gives packages the integration that matters (with, has, serialization, includes) while committing
only a key-based contract that doesn't leak the loading internals. A can follow later if a use case needs more,
for example custom through relations or create-through-relation. A generic Model::query(), part of D, is worth
doing in any case.
Happy to prepare a PR for whichever alternative you prefer. For B, that would be the public trait, the adapter to
AnyRelation, the #[relation(custom = ..)] attribute, and tests that port belongsToJson (eager loading,
nested loading, has, with_count) on SQLite, PostgreSQL and MySQL.
- Dominant language
- Rust
- Stars
- 847
- Forks
- 174
- Avg merge
- 5h 40m
- Merged PRs (30d)
- 167
Getting set up
This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from laravel/rust-framework
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
laravel/rust-framework#864 ·
Maintainers usually reply within 1 day
-
Difficulty 3/5 1-2 days Newbie friendliness 64/100
laravel/rust-framework#876 ·
Maintainers usually reply within 1 day
-
Case-sensitive contains, starts_with and ends_with that match % and _ literally on every databaseOpen
Difficulty 4/5 3-5 days Newbie friendliness 58/100
laravel/rust-framework#874 ·
Maintainers usually reply within 1 day
-
Difficulty 5/5 Over a week Newbie friendliness 35/100
laravel/rust-framework#873 ·
Maintainers usually reply within 1 day
-
Difficulty 4/5 3-5 days Newbie friendliness 58/100
laravel/rust-framework#872 ·
Maintainers usually reply within 1 day
All issues in laravel/rust-framework
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 83/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
neuralmagic/crucible#579 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 62/100
eclipse-score/kyron#249 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 67/100
seanmonstar/reqwest#3157 ·
Maintainers usually reply within 2 days