Relations resolve themselves
Declare a SeaORM relation on an exposed entity and the GraphQL field, the loader, and the auth scope appear with it.
Declaring a SeaORM relation on an exposed entity — and marking the
relation field #[expose] — is the whole
field-resolver story for entity-to-entity links — no
#[field_resolver], no #[dataloader] to write by hand. Pass
service = … to #[expose] and the macro emits the PK loader on the
service, the trait bridges that let other entities reach it, and a
#[ComplexObject] field resolver on the wire DTO. The ambient
Ability filters every batch under Repo::scoped(Action::Read), so a
relation cannot leak across orgs.
The declaration
Section titled “The declaration”use nest_rs::seaorm::expose;use sea_orm::entity::prelude::*;
#[expose(name = "User", service = super::service::UsersService, graphql)]#[sea_orm::model]#[derive(Clone, Debug, DeriveEntityModel)]#[sea_orm(table_name = "user")]pub struct Model { #[sea_orm(primary_key, auto_increment = false)] #[expose] pub id: Uuid, #[expose] pub org_id: Uuid, #[expose] pub name: String,
#[sea_orm(belongs_to, from = "org_id", to = "id")] #[expose] pub org: HasOne<crate::orgs::Entity>,}#[expose(name = "Org", service = super::service::OrgsService, graphql)]#[sea_orm::model]#[derive(Clone, Debug, DeriveEntityModel)]#[sea_orm(table_name = "org")]pub struct Model { #[sea_orm(primary_key, auto_increment = false)] #[expose] pub id: Uuid, #[expose] pub name: String,
#[sea_orm(has_many)] #[expose] pub users: HasMany<crate::users::Entity>,}That is the whole declaration — both directions now query:
$ curl -sX POST http://localhost:3000/graphql -d \ '{"query":"{ users { id org { id name } } orgs { users { edges { node { name } } } } }"}'What the macro emits
Section titled “What the macro emits”Per #[expose(service = …)]:
- A PK loader on the service:
<Service>ById(e.g.UsersServiceById,OrgsServiceById). Reads the parent’s primary key, returns the wire DTO. - For every
belongs_torelation, an FK loader on the FK-owning service:<Service>By<FkCol>(e.g.UsersServiceByOrgId). Its key carries the page window as well as the parent id, so two selections asking for different pages of one relation cannot be served the same batch entry. - The trait impls (
PkLoadable,RelatedTo<Parent, Via>) that let the inverse side reach the loader without naming the other service directly. - A
#[ComplexObject]field resolver on the wire DTO that calls into the loader and shapes the result.
The schema you get:
type User { id: String! name: String! """ Field-level authorization applies: reads `null` where the caller's ability withholds it. """ org: Org # belongs_to side — PK loader on OrgsService orgId: String!}
type Org { id: String! name: String! # has_many side — FK loader on UsersService, paged users(after: String, first: Int): UserConnection!}The has_many side is a Relay connection, not a list: edges { cursor node }
plus pageInfo, with the child’s own primary key as the cursor — the same keyset
Repo::page uses everywhere else. first defaults to 20 and is clamped to
1..=100 by clamp_page_size, so a relation over millions of rows is walked a
page at a time. Pass endCursor back as after to read the next page; an
after no page issued is an INVALID_ARGUMENT field error naming after,
never the first page.
$ curl -sX POST http://localhost:3000/graphql -d \ '{"query":"{ users { id posts(first: 1) { edges { cursor node { id } } pageInfo { hasNextPage endCursor } } } }"}'{"data":{"users":[ {"id":"…ac00","posts":{"edges":[{"cursor":"019ff…","node":{"id":"019ff…"}}], "pageInfo":{"hasNextPage":false,"endCursor":"019ff…"}}}, {"id":"…ac01","posts":{"edges":[{"cursor":"…b001","node":{"id":"…b001"}}], "pageInfo":{"hasNextPage":true,"endCursor":"…b001"}}}]}}Every parent gets its own page. That is a property of the query, not of the
buffer: the batch ranks rows within each parent
(ROW_NUMBER() OVER (PARTITION BY fk ORDER BY pk)) and keeps the first
first + 1 of each, in one round trip. A single LIMIT over
WHERE fk IN (…) cannot do this — it bounds the result set, so the parents that
sort first consume the budget and the rest come back empty, which reads exactly
like having no children.
The cross-entity rule
Section titled “The cross-entity rule”The FK loader belongs to the owner of the FK column — never the
consumer. Users.org_id lives on the users table, so
UsersServiceByOrgId is on UsersService. The orgs resolver reaches
it through a trait bridge, not by depending on UsersService directly.
This is the same hexagonal rule the rest of the framework follows:
when one service needs to touch another entity, it goes through the
owner’s service — never the ORM. Within a feature’s graphql/
adapter, the resolver only injects its own service; the auto-emitted
relation glue handles the rest.
Auth-scoped batches
Section titled “Auth-scoped batches”Every relation batch runs through Repo::<Entity>::scoped(Action::Read)
against the ambient Ability. A user without read access to Org
asking for user.org { name } gets null for that field, not an
error — the row does not pass the filter. A guarded GraphQL
request always carries an Ability (the guard seeds it per operation);
the ability-less unscoped path is the worker/queue side, not a request
transport — see Repo and executor.
This is the killer property: turning a per-row leak into a wire-level
omission needs no controller code and no manual if in the resolver.
The batch decides the rows and the caller’s grants their columns: each row it answers
is a wire row judged for the caller whose request runs the batch, as a root field’s
is, so under a .fields([Id, Name]) grant on User, post.author { id name }
answers and post.author { email } reads null, the column declared
#[expose(nullable)] as a grant withholding it needs
(Response masking).
What fails if you get it wrong
Section titled “What fails if you get it wrong”A batch runs on its own task — that is what a DataLoader is — and carries
what its request carries: the executor SeaOrmDatabaseModule installs around
/graphql, as the pool, and the ability the endpoint’s guards attach.
There is nothing to bind for it.
Two wiring mistakes stop the boot, each naming the line to add:
-
SeaOrmDatabaseModulenot imported. The service a GraphQL-exposed entity names (#[expose(service = S, graphql)]) hosts loaders that runRepo, which needs the unit of work the binding provides, so the app is refused at boot:Terminal window unmet dependency: `UsersService` (in module `UsersModule`) depends on `dyn UnitOfWork`, which no module this app imports provides. Import exactly one unit-of-work binding: `nest_rs::seaorm::SeaOrmDatabaseModule` runs every edge's units of work over SeaORM's executor. -
The target’s module not imported. A relation the schema serves reads a loader of the target entity’s service; when the app does not reach that service, the schema build refuses, naming the field, the entity declaring it and the module to import —
`User.org` (declared on `features::users::entities::user::Entity`) reads a loader of `features::orgs::service::OrgsService`: import `OrgsModule` into the module serving `User`. A relation on an object the schema does not serve is no defect of this app: its loader is only counted, once, atwarn(dataloaders linked but unreachable).
Without those guards there is no ability, and Repo denies every row,
saying so at warn on nest_rs::orm.
Fanout-aware complexity
Section titled “Fanout-aware complexity”A relation’s field scores what it resolves: a HasMany its page times each row,
a BelongsTo the additive default. Field complexity
is the formula, and #[expose(complexity = …)] its
override.
Opt out: leave a single relation unexposed
Section titled “Opt out: leave a single relation unexposed”Leaving a relation field unexposed (no #[expose]) keeps auto-emission off for
that field alone, and a #[field_resolver] owns it in the shape you need —
Field resolvers shows the
opt-out and a filtered replacement.
Two foreign keys to one parent
Section titled “Two foreign keys to one parent”A child can point at the same parent twice — a ticket with a reporter_id
and an assignee_id. Nothing in the type of that relation tells the
parent’s side which column to follow, so it says so:
#[sea_orm(has_many, relation_enum = "Reported", via_rel = "Reporter")]#[expose(via = "reporter_id")]pub reported: HasMany<crate::tickets::Entity>,
#[sea_orm(has_many, relation_enum = "Assigned", via_rel = "Assignee")]#[expose(via = "assignee_id")]pub assigned: HasMany<crate::tickets::Entity>,via names the child’s column; relation_enum / via_rel are SeaORM’s own
way of telling two relations to one entity apart, and belong to the entity
file either way. The child side needs nothing new — it already names its
column in #[sea_orm(belongs_to, from = "…")], so writing via there is a
compile error pointing back at from.
Leaving it out when it is ambiguous does not compile. A child that reaches
one parent through exactly one key gets a default; a child with two gets none,
and the inverse relation fails with the note telling it to name a column. The
one thing that never happens is the framework picking whichever belongs_to
came first.
Advanced: bidirectional and multi-hop graphs
Section titled “Advanced: bidirectional and multi-hop graphs”You can skip this on a first read — it only matters once a schema grows bidirectional or multi-hop relations.
Bidirectional and multi-hop graphs (org ↔ membership ↔ user) are resolved
explicitly rather than guessed. Composite primary keys are refused at compile
time (not a cryptic E0119). See
crates/nest-rs-seaorm-macros/src/relations.rs for the diagnostics.
Going further
Section titled “Going further”- Dataloaders — write a custom batch loader
(
by_name,by_tag, denormalized lookups) when the auto-emitted PK + FK loaders don’t fit. - Field resolvers — the
leave-it-unexposed escape hatch, and the single-
ComplexObjectrule in detail. - Database — the service contract every loader (auto-emitted or hand-rolled) routes through.