Allow packages to define their own relation types

Open
#498 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Active
Tech stack
rust
Domain
backend, databases

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:

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:

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_missing and 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>() (the Model trait has no generic
    query()) and Column::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. AnyRelation exposes Aggregate, Inverse, JoinTable, SetParent,
    Location, join_parent for 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, respect CHUNK, and handle OfMany.
  • 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 and Slot. with, nested eager loads, serialization, try_loaded and 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
    needs existence, and for JSON relations that needs a correlated JSON containment. Today Expr::json_contains
    only takes a bound value, so a column operand, as in Eloquent's whereJsonContains with 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

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from laravel/rust-framework

All issues in laravel/rust-framework

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.