Skip to content

Relationship endpoints in the bundle

The core library owns the relation DSL — BelongsTo/HasMany/BelongsToMany/MorphTo (HasMany is the plain to-many, BelongsToMany the pivot-backed to-many — see core relations), the related type as a mandatory make() argument (BelongsTo::make('owner', 'users')), the paginate()/withData() builders, the withoutLinks()/cannotReplace() exposure flags, and the rendering of linkage, self/related links and ?include. Read core relations and core related-endpoints for that vocabulary.

This page covers what the bundle adds: the Symfony routes for each relation, the handler-side enforcement of per-relation exposure gates, the storage-correct mutation seam, the queryable/paginated related-collection seam, and how polymorphic and resource-less relations wire up. Every relation you declare on a resource — or standalone via #[AsJsonApiRelations] — gets the full relationship endpoint set automatically, with no extra routing.

The two read endpoints per relation

For any type that declares relations, the bundle's route loader emits two read paths per relation, both parametric in {relationship} (written {rel} for short in the path tables below):

Endpoint Path Renders
related GET /{type}/{id}/{rel} the related domain value(s) as full resources
relationship (linkage) GET /{type}/{id}/relationships/{rel} resource-identifier objects only

Linkage and the convention self/related links render on the parent's own read too (GET /tracks/1), default on. A to-one with no related object renders data: null (not a 404), and ?include flows through both the parent read and the related endpoint. The relationship endpoint renders linkage only, never an included member, but it still checks ?include. Its paths start at the parent, as in the spec's GET /articles/1/relationships/comments?include=comments.author, and a path naming a relationship the parent's tree doesn't have is a 400 INCLUSION_UNRECOGNIZED, checked before the parent loads. A PATCH, POST or DELETE that answers with its linkage checks ?include the same way, before it writes. A write-only relation's mutation answers 204 with no document, so it ignores ?include, as a delete does. The relation DSL drives all of this — see core relations (withoutLinks()) and core sparse-fieldsets-and-includes (?include).

The bundle's job is the wiring. TrackResource declares a to-one album and a plain to-many playlists (the pivot-bearing variant lives on the playlists resource's orderedTracks — see Pivot (belongsToMany) data):

BelongsTo::make('album', 'albums'),
BelongsToMany::make('playlists', 'playlists')
    ->cannotReplace()
    ->countable(),

and GET /tracks/1 renders each relationship with linkage plus the two convention links, exactly as the RelationshipReadTest asserts:

"relationships": {
  "album": {
    "data": { "type": "albums", "id": "1" },
    "links": {
      "self": {
        "href": "https://music.example/tracks/1/relationships/album",
        "describedby": "/docs.json#/paths/~1tracks~1%7Bid%7D~1relationships~1album/get"
      },
      "related": {
        "href": "https://music.example/tracks/1/album",
        "describedby": "/docs.json#/paths/~1tracks~1%7Bid%7D~1album/get"
      }
    }
  }
}

Load-state-aware linkage

A to-many (and a HasOne) is lazy by default, rendering the convention links without forcing a fetch; withData() opts one back to eager. On the Doctrine path the bundle backs the lazy default with a storage-aware load-state seam (DoctrineRelationshipLoadState, owned by doctrine.md): an uninitialised PersistentCollection reports "not loaded", so the rendered relationship carries links but omits the data member. AlbumResource's HasMany::make('tracks') keeps the lazy default, and GET /albums/1 renders tracks with links and no data, while the explicit GET /albums/1/relationships/tracks serves its first page of identifiers.

Relations read through a foreign key

A HasMany or HasOne declared with a foreign key, its third argument, is read through the related type's field or to-one relation that holds the parent's id, never off the parent model. The music catalog's stations are served by StationProvider from a fixed list, with no database behind them, and their plays live in Doctrine:

// src/Resource/StationResource.php
HasMany::make('plays', 'plays', 'station'),

GET /stations/kexp/plays, GET /stations/kexp/relationships/plays, GET /stations?include=plays, withData() linkage, ?withCount=plays, offset and cursor pages, a relatedQuery and the related type's filter defaults are all the plays whose station is the station's id, as the plays type's provider scopes them. Each read covers the whole page of parents: the reference Doctrine provider runs it as one WHERE station IN (:keys) query with the related type's query extensions applied, windowed per parent like any rendered first page, and one grouped query for a count. The in-memory provider matches its stored rows the same way.

Use it wherever the parent can't hold the relation: a singleton or computed type served by a custom provider, or an entity with no inverse mapping to the rows that point at it. Once declared, the foreign key decides every read of the relation even when the parent's entity maps an association for it.

The foreign key names a stored field of the related type holding the parent's id, the parent's wire id decoded through its id encoder, or a to-one relation to the parent's type, which on Doctrine is a single-valued association to the parent's entity. Warm-up checks it, and checks that the related type's provider reads through foreign keys (ReadsByForeignKeyInterface, which the Doctrine and in-memory providers implement).

Doctrine compares the key in its database form on both sides, through the field's own mapped type: the parents' keys are converted before they're bound, and each row's key is converted before it's matched back to its parent. A field of any type works, an integer, a string, a guid, a Symfony uuid or ulid kept as 16 bytes on a platform with no native uuid column, or a custom type holding a value object, and so does a parent type behind an id encoder.

A WhereHas, WhereDoesntHave or ->through() path over such a relation joins the rows whose key names the row being filtered, so it needs SQL to compare the field with the parent's id column as stored. Warm-up refuses a filter reaching through one whose field and id column differ in type, other than both being integers or both text. Such a join compares the storage key, so a polymorphic id stored as the wire id of a type with an id encoder doesn't match there. The in-memory provider walks the same relation through the related type's provider, so its filters match what Doctrine's do.

A foreign key through a polymorphic relation

When the related rows point back through a MorphTo that keeps its target in two fields, declare the inverse with MorphMany or MorphOne, naming the MorphTo:

// NoteResource
MorphTo::make('owner', ['posts', 'videos'])
    ->identifiedByColumns(type: 'ownerType', id: 'ownerId'),

// PostResource
MorphMany::make('notes', 'notes', 'owner'),
MorphOne::make('latestNote', 'notes', 'owner'),

They build the same HasMany and HasOne as naming the MorphTo with HasMany::make() or HasOne::make(), and warm-up refuses them unless the member is a MorphTo. On Doctrine it must be declared with identifiedByColumns(). The id field may hold the parent's storage key or its wire id, and a uuid in either case, and every read matches all of them. A page of parents is still read in one windowed query, partitioned by the lower-cased column, when each parent's forms differ only in letter case. Only where an id encoder stores a really different form, such as a prefixed wire id beside the storage key, are a parent's pages read one parent at a time.

Every read and filter of the relation then keeps both fields: the type field to the stored values naming posts, and the id field to the posts' keys, so a video's notes never show up under a post whose id they share. A relationship write sets both fields on the rows that join and clears both on the rows that leave, through WritesPolymorphicForeignKeysInterface, which the Doctrine and in-memory persisters implement. Naming the id field itself, HasMany::make('notes', 'notes', 'ownerId'), fails warm-up and tells you to name the MorphTo instead.

A relation with no foreign key on a type no entity maps can't be scoped by Doctrine, so it reads what the parent model holds. A to-many's pages, counts and related endpoint are cut in memory from the model's value, unless the parent type's provider batches the relation itself, and a HasOne reads its target off the model. When the related type is scoped by a query extension that read can't be scoped to the parent, so warm-up refuses a to-many into it unless it declares a foreign key or extractUsing(). The exception is a to-many that no request reads, which needs neither:

  • A writeOnly() relation on a type whose operations leave out Update is set only by a create, and nothing renders it. With Update, replacing its members reads the current ones, so it is still refused.
  • Every relation of a relatedOnly type that no relation targets and no action answers with is never read. Such a type is only ever an action's inputType, hydrated from the request document.

The warm-up message names the foreign key, extractUsing() and writeOnly(). A belongsToMany with stored pivot fields reads its association entity through the parent's mapping, so warm-up refuses it on such a type.

Writing through a foreign key

A relationship write of a relation declared with a foreign key never reaches the parent type's persister. The related type's persister sets the foreign key on the rows the linkage names and clears it on the rows that leave:

  • a replace points the linked rows at the parent and clears the members it leaves out;
  • an add points the linked rows at the parent, taking each from any parent it had;
  • a remove clears the linked rows that are members, and leaves any other row alone.

A field takes the parent's id as storage holds it, and a to-one relation takes the parent itself. The members are the ones the relation's reads serve, so a replace leaves alone a row the related type's scope hides. A write that would clear a foreign key storage requires, a NOT NULL column on Doctrine, is refused with the 403 of the mutation that drops the member, linkage naming a row the related type doesn't serve is a 404, and a row taken from another parent is authorized as a member move. readOnly(), cannotReplace() and the other gates and cannotChangeMembership() work as on any relation. It runs in the parent write's transaction, with the related persister's own transaction joined to it, inside an Atomic Operations batch as well, and the before and after relationship hooks, afterCommit callbacks and scopes all apply as usual. A foreign-key relation in a create body is written once the parent exists, since its id is what the rows hold.

The Doctrine and in-memory persisters write foreign keys through WritesForeignKeysInterface; a related type whose persister doesn't implement it can't be written this way. Doctrine converts the key to the field's PHP form first, so a uuid field gets a Uuid. A Doctrine parent with no inverse mapping to its members, which used to fail on a relationship write, now writes through its foreign key.

Rendered to-manys show their first page

Wherever a to-many's data renders, included or declared withData(), it is the first page its related endpoint serves under the relation's paginator, and its links carry first, next and, for a counted page, last. included holds the same members. A paginated to-many the model happens to hold loaded still renders only its first page. Declare withoutPagination() on a relation whose whole set should render.

GET /{type}/{id}/{rel} for a to-many is a real collection endpoint: it honours ?filter/?sort/?page against the related type's vocabulary, not the parent's. The bundle resolves this through a dedicated SPI seam, DataProvider::fetchRelatedCollection() (signature in data-layer.md) — so a custom provider can scope or replace it, and the Doctrine reference never loads the whole collection.

Per-relation default pagination resolves along a chain: the relation's own paginator → the related resource's paginator → the server default. The Doctrine push-down (FK fast-path vs IN-subquery for many-to-many) is owned by doctrine.md; the in-memory provider reads the related objects off the parent and applies the shared CriteriaApplier plus an array window.

The RelatedCollectionTest witnesses both branches. albums.tracks paginates two-per-page (declared on the album's HasMany('tracks')->paginate(PagePaginator::make()->withDefaultPerPage(2))), and ?filter/?sort scope against the tracks vocabulary — so the related type's own default filter even hides the explicit track:

GET /albums/1/tracks                  → tracks 1, 3 (track 2 is explicit, filtered out), page meta
GET /albums/1/tracks?sort=-title      → tracks 3, 1
GET /albums/1/tracks?filter[explicit]=true → track 2
GET /tracks/1/playlists               → unpaginated (the relation declares no paginator)

A relation that declares no paginator renders its related collection without page meta — that is the unpaginated baseline.

The to-many relationship (linkage) endpoint GET /{type}/{id}/relationships/{rel} is queryable at the same parity: ?filter/?sort/?page scope against the same merged vocabulary and pagination is on by default (the same relation → related resource → server-default chain). It renders the windowed page-1 linkage (resource identifiers), and — because the spec puts a relationship's pagination in its own links object, not the document meta — its first/prev/next(/last) links ride the relationship document's links (the convention self stays the bare endpoint URL). The RelationshipReadTest witnesses it:

GET /albums/1/relationships/tracks                  → ids 1, 3 (track 2 is explicit, filtered out)
GET /albums/1/relationships/tracks?sort=-title      → ids 3, 1
GET /albums/1/relationships/tracks?filter[explicit]=true → id 2
GET /albums/1/relationships/tracks?page[size]=1     → id 1, with a `next` link to page 2

A pivot (belongsToMany) to-many relationship endpoint is queryable too: it windows the linkage, scopes the related + pivot vocabulary, and still renders each member's meta.pivot (the PivotTest witnesses GET /playlists/{id}/relationships/orderedTracks?sort=position&filter[position]=…&page[size]=…). A polymorphic (MorphToMany) to-many relationship endpoint, over one type or several, cannot window mixed linkage — querying it is unsupported, so a ?filter/?sort/ ?page there is a clean 400 (its OpenAPI operation advertises no query parameters), while a bare GET …/relationships/{morphMany} still renders the whole mixed linkage.

Filtering a to-one relationship

A to-one is not a collection, so it does not paginate or sort — but it can carry a relation-scoped ?filter that decides whether its target is rendered at all. Give a to-one relation a withFilters(...) over a column on its related type, and the filter applies as a predicate on the target: when it excludes the target, the to-one renders data: null instead of the resource. A 200 with data: null, never a 404 — the relationship exists, the filter just matched nothing.

AlbumResource scopes filter[name] (the related artists.name column) onto its artist to-one:

BelongsTo::make('artist', 'artists')
    ->withFilters(Where::make('name', 'name')),

The filter reaches the to-one on all three read surfaces, each nulling the target when it doesn't match (album 1 belongs to Radiohead):

# related endpoint — full resource, or data: null
GET /albums/1/artist?filter[name]=Radiohead   → data: { type: artists, id: 1, … }
GET /albums/1/artist?filter[name]=Portishead  → { "data": null }   (200, not 404)

# relationship (linkage) endpoint — identifier, or data: null
GET /albums/1/relationships/artist?filter[name]=Radiohead   → data: { type: artists, id: 1 }
GET /albums/1/relationships/artist?filter[name]=Portishead  → { "data": null }

The third surface is the Relationship Queries profile on a primary request: a relatedQuery[<toOneRel>][filter] that excludes the target renders the linkage null and drops the target from included:

GET /albums/1?include=artist&relatedQuery[artist][filter][name]=Radiohead
  → data.relationships.artist.data = { type: artists, id: 1 }, included = [artist 1]
GET /albums/1?include=artist&relatedQuery[artist][filter][name]=Portishead
  → data.relationships.artist.data = null, included = []

The profile filters a to-one of the rendered resource. On the related endpoint the target is the primary data, so GET /albums/1/artist?relatedQuery[artist][filter][…] does not filter the artist: artist must name a relation of artists, and is a 400 when it doesn't. The relationship endpoint renders linkage, not resources, and ignores relatedQuery.

relatedQuery on a to-one is [filter] only — a [sort] or [page] on a to-one path is a 400 (a to-one is not a list); see the profile section's to-one bullet. The custom-provider seams behind this are relatedToOneMatches() / relatedToOneMatchesBatch() on DataProviderInterface (returning false nulls the target; the batched twin answers a whole page of parents at once so an include does not N+1); the feature is monomorphic — a MorphTo to-one is out of scope. The RelationshipReadTest and RelationshipQueriesProfileTest witness all three surfaces on Doctrine.

Counting relations (countable() and ?withCount)

Mark a to-many relation countable() to opt it into counting (off by default). The count is pushed down (never materialising the collection) and batched across a page of parents (one grouped count per relation, no N+1):

HasMany::make('tracks', 'tracks')->countable();

Counting is exposed two ways, both on the total meta key:

  • ?withCount=rel1,rel2 — a flat primary-request parameter naming relationships (like ?include) — adds meta.total to each named relationship object when the parent is rendered: a fetched resource, the resource a create, an update or an action answers with, a to-one related read, every parent of a collection, and a related-collection member. The generated OpenAPI document offers withCount on each of those operations with the countable relations of the type it renders, and offers _self_ only where there is a collection to total. withCount is the Countable profile's family (the bundle registers and advertises it), so a client opts in by negotiating the profile URI in the Accept header's profile parameter — without it the family is unrecognized (a 400 under strict validation):
Accept: application/vnd.api+json;profile="https://haddowg.github.io/json-api/profiles/countable/"

GET /albums/1?withCount=tracks         → data.relationships.tracks.meta.total
GET /albums?withCount=tracks           → every album's tracks.meta.total (counted in ONE grouped query)

The total is gated by countable() and being named in ?withCount (with the profile negotiated). A ?withCount naming a relation that is not countable(), naming a to-one, or naming an unknown relationship is a 400 (source.parameter: withCount).

  • The related-collection endpoint (GET /{type}/{id}/{rel}) is count-free by default, exactly like a primary collection: it windows without a COUNT — no total, no last, a further page signalled by next. A client opts into the total with ?withCount=_self_ on a countable() relation under the Countable profile (the _self_ token meaning "this related collection"); an author can make it always count with withCount() on the relation's paginator. The gate is universal — it applies to a pivot (belongsToMany) relation's endpoint exactly as to a plain one.

Behaviour change. Related collections are now count-free by default (matching primary collections). The meta.page.total + last link (and the top-level meta.total) return only under ?withCount=_self_ on a countable() relation, or with withCount() on the relation's paginator. The related-endpoint _self_ count is gated by the relation's countable() (not the related-type resource's): core's document gate is relation-aware on a related render via the relation's countability threaded through RelatedResponse.

?withCount counts the relation's filtered set. The count reflects the SAME filters the related-collection endpoint applies: a relation's own filters(), the related resource's filter defaults (less any the relation drops), and any relatedQuery[<rel>][filter] the request carries through the Relationship Queries profile. So ?withCount=tracks of a relation whose related resource defaults explicit=false reports the default-scoped total, and ?withCount=tracks&relatedQuery[tracks][filter][explicit]=true counts only the matching members — exactly the totals GET /albums/{id}/tracks (with the same filter) pages. A parent with no matching member reports 0. The common case — a relation with no filter and no filter defaults, with no relatedQuery filter — is raw membership, unchanged.

Behaviour change. ?withCount used to count raw membership and ignore any active relation filter. It now counts the filtered set, so a relationship object's meta.total can be smaller than in prior releases — it now equals the related endpoint's filtered total. This includes filter defaults: a related resource with a default filter narrows the count even without an explicit relatedQuery filter.

A pivot (belongsToMany) relation counts distinct far members — so duplicate membership (the same member joined to the parent by more than one association row, a track at two positions) counts once, matching the related-collection endpoint (which dedupes to one row per member) and the rendered linkage. The ?withCount relationship-object total and the endpoint pagination total therefore report the same number for the same relation/parent. A polymorphic MorphToMany is counted by the in-memory provider (the mixed member set) but, over several types, is unsupported by the Doctrine reference provider (its members span entity classes) — supply a custom DataProvider if you need it on Doctrine.

A response whose primary data mixes types, such as a polymorphic MorphToMany's related page or a custom action answering with several types, accepts ?withCount=<rel> when at least one member type counts <rel>. Each member renders its own meta.total where its type counts the relation, and the others carry none. Nothing is summed across types. A name no member type counts is still a 400. An action building its own PolymorphicSerializer passes the member serializers as its second argument, or nothing on the response is countable.

Relation-scoped filters and sorts

A relation can declare its own filters()/sorts() that augment only its related-collection endpoint GET /{type}/{id}/{rel} — never the primary /{relatedType} collection. Declare them with the relation builders withFilters(...)/withSorts(...):

HasMany::make('tracks', 'tracks')
    // Available ONLY on GET /playlists/{id}/tracks, not on GET /tracks:
    ->withFilters(Where::make('titleContains', 'title', 'like'))
    ->withSorts(SortByField::make('recent', 'id'));

The bundle merges this scoped vocabulary with the related resource's own when it parses the request's ?filter/?sort on the related endpoint:

  • effectiveFilters = relatedResource->filters() + relation->filters()
  • effectiveSorts = relatedResource->allSorts() + relation->sorts()

so both apply together. On a key clash (the same filter[…]/sort key declared on both the related resource and the relation) the relation's declaration wins — it is the more specific scope. A filter or sort family and an exact key equal to its prefix don't clash, since a family never answers its bare prefix, so both stay. A key in neither set still 400s (filter[unknown] → an unrecognized-parameter error; sort=unknown → SORTING_UNRECOGNIZED), unchanged.

The scoping is load-bearing: a relation-scoped key reaches GET /{type}/{id}/{rel} only. On the primary /{relatedType} collection — where just the related resource's own vocabulary applies — the relation's key is unrecognized and 400s. This is why a contextual or pivot-derived filter/sort belongs on the relation: it stays scoped to the one endpoint where it is meaningful.

A relation-scoped filter/sort operates on the related entity (the common case) and works out of the box. A filter/sort that reads a pivot/join-table column is handled separately — see Pivot (belongsToMany) data below.

A filter default on the related type narrows every read of a to-many to that type, not only /{relatedType}. When a relation should list every member, drop the default on the relation with core's withoutFilterDefaults(). Name keys to drop only those defaults, or pass none to drop every default the related type declares:

// TrackResource declares Where::make('explicit')->asBoolean()->default(false)
HasMany::make('tracklist', 'tracks')
    ->storedAs('tracks')
    ->withoutFilterDefaults('explicit'),

The relation then reads its members without that default on all of these: its linkage, ?include and its batching, ?withCount, the related and relationship endpoints, and a Relationship Queries relatedQuery window. The filter itself stays. GET /albums/1/tracklist?filter[explicit]=false still narrows the members, and relatedQuery[tracklist][filter][explicit]=… works too. /tracks keeps its default. A default the relation declares on its own withFilters() filter still applies.

Each named key must be a filter of the related type that declares a default. The bundle checks this at cache:warmup, beside the relation's default read order, so a typo fails cache:clear rather than the first request. A polymorphic MorphToMany has no shared filter vocabulary in the bundle, so no related-type default applies to it in the first place; the warm-up check still accepts a key defaulted on any one of its related types.

The OpenAPI document follows the same rule. A filter default shows as the default of its filter[<key>] parameter's schema, and the relation's related and relationship endpoints leave off each default the relation drops. On the example's /albums/{id}/tracklist, filter[explicit] has no default, while /albums/{id}/tracks shows default: false.

Once a relation drops every default it would have applied, and it is unordered and its related type unscoped, its linkage reads straight off the model again instead of through the related type's provider.

The music-catalog example's album declares tracklist this way, beside the default tracks:

GET /albums/1/tracks     → tracks 1, 3 (track 2 is explicit, filtered out)
GET /albums/1/tracklist  → tracks 1, 2, 3
GET /albums/1/tracklist?filter[explicit]=false → tracks 1, 3

A relation's default read order

A to-many reads its members in a declared order when the request names no sort. Declare it on the relation with defaultSort(), taking the same directives as a resource's defaultSort(); for that relation it replaces the related type's own default. Without one, the related type's default applies, and without either the members come in the order the store returns them.

HasMany::make('tracks', 'tracks')
    ->defaultSort(new SortDirective(SortByField::make('title'), descending: true));

The order applies on every read of the relation, so they all agree: its document linkage, ?include and the include batching behind it, a Relationship Queries window, the relationship endpoint and the related endpoint. A requested sort, on an endpoint or as a relatedQuery[<rel>][sort], replaces the whole default.

Applying the order to linkage means the members have to be read through the provider, so a to-many with a default read order loads in one ordered query per relation across a page of parents, even when it isn't included. A to-many with no order whose provider doesn't scope related reads renders the members the model holds. When its linkage renders without an include and the model hasn't loaded the collection, the bundle loads it for the whole page in one query per relation rather than one per parent.

Each key must name a sort the relation accepts: one of the related type's sorts, a withSorts() sort or, on a pivot belongsToMany, a pivot field. A pivot key orders by the pivot field's stored column on every path, include batching included. The container warm-up checks the keys, so a typo fails cache:clear rather than every read. It also refuses a pivot key, or a sort that reaches through the pivot row such as SortByField::make('added', 'addedAt')->through('pivot'), on a relation whose related type is served by a provider that doesn't query pivot rows, such as the in-memory provider, and names the relation and the sort. The OpenAPI document states the relation's own order as the default of the sort parameter on its relationship and related endpoints; the related type's default isn't the relation's, so it isn't stated there.

Members kept in position order (positionedBy())

A to-many can keep its members in an order the client controls. positionedBy() names a stored Integer field holding each member's position: a pivot field on a belongsToMany or an identified MorphToMany, or a field of the related type on a hasMany.

HasMany::make('tracks', 'tracks')->positionedBy('position');

BelongsToMany::make('tracks', 'tracks')
    ->through(PlaylistTrack::class)
    ->fields(Integer::make('position'))
    ->positionedBy('position');

The linkage a client sends is the only way to change a position:

  • a replace, on the relationship endpoint or as the relation's linkage in a whole-resource PATCH, writes each member's index in the linkage, from 0;
  • an add appends the new members after the current highest position, in linkage order, and leaves the others where they are;
  • a remove leaves gaps and renumbers nothing.

Clients never write a position. A pivot position is read-only on the relation, and a hasMany's field has to be declared ->readOnly() on the related type, which the container warm-up checks along with it being a stored Integer. The position is the relation's default read order, ascending, unless it declares a defaultSort(), and a positioned hasMany accepts sort by its position field on its endpoints even when the related type doesn't sort by it; the OpenAPI document lists that sort.

A position column is normally unique per owner, so writing positions in place would collide with rows that haven't moved yet. The Doctrine persister writes them in passes, flushing after each inside the write's transaction: the removed members go and any new member is written at a temporary position past every one in use, then each member that moves takes a temporary position, then everything takes its final one. A parent being created holds no positions yet, so it takes them in one write. A unique key over the owner and the position is safe.

A MorphToMany declared with identifiedByRows() takes its positions from the plan core computes for every write: the persister deletes the removed rows, moves the rows that change to temporary positions, updates the kept rows, then inserts the new rows already at their final positions, flushing after each pass. Since no row is ever written without its position, the position column can be NOT NULL. A MorphToMany read through an identifiedBy() closure still has its rows decided by its fillUsing() hook, and the bundle writes their positions afterwards in the passes above, a new row starting at a temporary position. The in-memory provider writes a hasMany's positions onto its members; it holds no pivot rows, so a positioned belongsToMany is Doctrine-only, and the warm-up refuses one whose related type the in-memory provider serves. A custom persister writes positions by implementing WritesPositionsInterface, which the handler calls with the column the position is stored in; core's Positions computes what to write.

Filtering and sorting a relationship from the primary request (the Relationship Queries profile)

The same scoped vocabulary is reachable from the primary request — without a second round-trip to the related endpoint — through the Relationship Queries profile (its specification lives on the core docs site, the URI it is negotiated by). The bundle registers and advertises it, so a client opts in by negotiating its URI in the Accept header's profile media-type parameter:

Accept: application/vnd.api+json;profile="https://haddowg.github.io/json-api/profiles/relationship-queries/"

With the profile negotiated, the client addresses a relationship by its include path and supplies a per-relationship sort / filter via the relatedQuery family (or the rQ shorthand; both are spec-compliant because each base carries an uppercase letter):

# order the included tracks by -duration, narrow them to one filter
GET /albums/1?include=tracks&relatedQuery[tracks][sort]=-duration&relatedQuery[tracks][filter][longerThan]=300

# the rQ shorthand is identical
GET /albums/1?include=tracks&rQ[tracks][sort]=duration

The family applies to every response that renders resources of one type: a collection or single read, a create answering 201 or an update answering 200 with its resource, a related read of a relation over one type, and a custom action answering with a resource. Its paths are relations of that rendered type. On a related endpoint they address the related resources' relations, never the target, and each related resource's linkage, included members and ?withCount total follow them exactly as a primary document's do: GET /artists/1/albums?include=tracks&relatedQuery[tracks][filter][longerThan]=300 renders each album's tracks narrowed by the filter. The OpenAPI document lists relatedQuery on exactly these operations, through one <Type>RelatedQuery parameter component per rendered type that names each addressable relation and its vocabulary.

A response rendering several types has no type to address, so any path on it is the 400 an unknown path gets: a related read of a MorphTo or MorphToMany, and an action answering with resources of more than one type. A delete, a relationship read or mutation, and an action answering without a resource render no resources and ignore the family.

A create or update checks its relatedQuery before it writes anything: an unknown path, sort or filter key, or a mistyped filter value fails the request with the same 400 and leaves nothing stored.

  • The client addresses a top-level relation of the request's primary resource by its name: a to-many or to-one over one type that a read renders. A polymorphic relation (MorphTo, MorphToMany, even over one type) shares no vocabulary and a write-only relation renders no linkage, so naming either is a 400. A dotted path (relatedQuery[tracks.album]) is legal family grammar — it parses without error — but the bundle windows only top-level relations, so a dotted path addressing a relation of an included resource resolves to no relation and is a 400 (address that relation at its own endpoint instead). An unknown relationship path is likewise the related-collection endpoint's same 400, with source.parameter the canonical relatedQuery[<path>]. A to-one path accepts [filter] only — a [filter] passes through and may null the linkage (see Filtering a to-one relationship), while a [sort] or [page] on a to-one is the same 400 (a to-one is not a list).
  • sort orders the relationship's linkage data (and so SELECTS which members land on the included page — see below). filter narrows the set against the related-collection endpoint's vocabulary (the related resource's filters/sorts merged with the relation's own scoped ones, exactly as above) — an unknown key is the same 400.
  • page is out for the profile: an addressed relationship always renders page 1 (the relation's default size), navigated via its own relationship-object pagination links, as every rendered to-many does without the profile too. So it carries first/prev/next (+last only when the page is counted) in its links object — in the spec's plain form against the relationship-linkage endpoint (/albums/1/relationships/tracks?sort=-duration&page[number]=2), never the relatedQuery[…] form (which only addresses a relationship from a parent request).
  • On a [path][op] conflict between relatedQuery and rQ, the canonical relatedQuery wins (the shorthand yields — not an error).
  • The family is ignored entirely when the profile is not negotiated (today's behaviour, no profile advertised) — so a relationship literally named after a reserved query family is safe.

The window only fires for a relationship whose linkage data actually renders in this document: a relation that is ?included at the primary level (default-includes honoured) or one that renders data unconditionally (withData()). A lazy, links-only, not-included to-many (the default — it renders convention links without forcing a fetch, see Load-state-aware linkage) is not windowed: addressing it with a relatedQuery sort/filter does not apply the criteria and does not force a fetch — it renders links-only exactly as the lazy default intends. To window and filter such a relation, ?include it (or declare it withData()). An unknown sort/filter key still 400s either way — addressing a relationship the request does not render is not a way to slip a typo through. The relationship count is unaffected: a ?withCount of a not-included, filtered to-many still reports the filtered total (the count loads nothing and is independent of the window).

Under ?include, the included resources reflect exactly that page-1 set — the sort selects the page. On a collection include (GET /albums?include=tracks) each parent's relationship is windowed to its own page 1 independently. Two relations over one storage column each render their own page, since a page reaches the document beside the model rather than written onto it.

Includes are batch-loaded built in — no extra dependency. The effective include tree is loaded one query per relation per level (no 1 + N) on both providers, driven by the same batched related-fetch seam these windowed includes use; see doctrine → eager-loading includes.

Filtering a collection by a relationship

The sections above filter a relationship's own related collection. This one is the inverse: filtering a primary collection by a condition on a relationship — "albums whose artist is named Radiohead", "albums that have at least one track". The core relation-existence filters (WhereHas/WhereDoesntHave) and the dotted traversal filter (WhereThrough) declare on the resource's filters() like any other filter and apply to its primary GET /{type} collection.

All three translate to a single correlated EXISTS (or NOT EXISTS) semi-join: set-membership, never a fetch-join, so the primary rows are neither duplicated nor in need of DISTINCT, the relation is never hydrated, and linkage / ?include / the relationship-queries profile all compose for free. A to-one and a to-many translate identically — "there exists a related row that …".

WhereThrough — dotted-path traversal (portable)

WhereThrough::make('artist.name') keeps a row whose artist relation's name matches — an EXISTS-ANY semi-join across the dotted path. Every intermediate segment is a relationship (to-one or to-many, both identical); the final segment is the compared attribute. The path chains: WhereThrough::make('author.company.name') hops two relations to a leaf column.

use haddowg\JsonApi\Resource\Filter\WhereThrough;
use haddowg\JsonApi\Resource\Filter\WhereHas;

public function filters(): array
{
    return [
        WhereHas::make('tracks'),       // albums that have at least one track
        WhereThrough::make('artist.name'), // filter[artist.name]=Radiohead
    ];
}

The wire key carries the dots by default — make('artist.name') responds to filter[artist.name] — or pass an explicit key (make('topArtist', 'artist.name') → filter[topArtist]). Because both positional slots are taken, the comparison operator is the fluent ->operator(...) setter (default =, same vocabulary as Where: =, !=, <>, >, >=, <, <=, like), and WhereThrough carries value constraints (->integer(), etc.) like any value filter — so a mistyped filter[…] is a clean 400 (FILTER_VALUE_INVALID) before the provider runs.

It is portable — it works on both providers. The in-memory provider traverses the object graph (core's ArrayFilterHandler); the Doctrine reference renders it as a correlated EXISTS subquery rooted on the related entity. AlbumResource declares it, and ReadQueryTest::aWhereThroughFilterTraversesTheArtistRelationByName witnesses it:

GET /albums?filter[artist.name]=Radiohead   → albums by Radiohead
GET /albums?filter[artist.name]=Portishead  → albums by Portishead
GET /albums?filter[artist.name]=Nobody      → data: []

WhereThroughIn and paths that end on a relationship

WhereThroughIn is WhereThrough with an IN at the leaf. The row matches when the value the path reaches is any of the requested values, so its value is always a list, sent delimited or as an array:

use haddowg\JsonApi\Resource\Filter\WhereThrough;
use haddowg\JsonApi\Resource\Filter\WhereThroughIn;

public function filters(): array
{
    return [
        WhereThroughIn::make('advertiser', 'campaign.advertiser'), // filter[advertiser]=4,7
        WhereThroughIn::make('template', 'templates'),             // filter[template][]=tpl-1&filter[template][]=tpl-2
        WhereThroughIn::make('advertiserName', 'campaign.advertiser.name'),
        WhereThrough::make('advertiserIs', 'campaign.advertiser'), // filter[advertiserIs]=4
    ];
}

Either filter's path may end on a relationship instead of a field. campaign.advertiser ends on the campaign's advertiser, and a single segment like templates ends on the type's own relation. The filter then compares the related resource's id. The client sends the wire ids it reads in data.id, and each one is decoded through the related type's id encoder before the query runs, so an id the encoder cannot decode is a 400 FILTER_VALUE_INVALID at the parameter. With no declared constraints the values take the related id's format: a numeric() id validates each member as an integer and a uuid() id as a UUID, and the OpenAPI document types the list items the same way.

The bundle resolves each path against the type the filters run against, the primary type on GET /{type} and the related type on a related or relationship endpoint, after matching the requested keys, so a filter family's filter resolves per request too. A path whose segments do not all name relations, matched by their storage name, ends on a field and behaves as it always did. The leaf must be monomorphic: a path ending on a MorphTo or MorphToMany fails cache:warmup, as does a relationship-ending WhereThrough with an operator other than = or != or a deserializeUsing().

Both providers run it. In memory, core's ArrayFilterHandler compares each related row's key. On Doctrine it is one correlated EXISTS with an IN over the decoded keys at the leaf, never one EXISTS per value, and an empty list matches nothing without an IN (). See doctrine for the SQL.

Filtering by a polymorphic relation: WhereMorph

Core's WhereMorph filters by what a MorphTo or MorphToMany stores, sent as a resource identifier:

use haddowg\JsonApi\Resource\Filter\WhereMorph;

public function filters(): array
{
    return [
        WhereMorph::make('subject')->describedAs('Items about this resource.'), // filter[subject][type]=rfps&filter[subject][id]=812,813
    ];
}

type is required and must be one of the relation's types, and id, comma-separated or filter[subject][id][]=…, is optional. Each id is checked against its type's id format and decoded through its encoder, so filter[subject][type]=rfps&filter[subject][id]=abc against a numeric() id is a 400 FILTER_VALUE_INVALID at filter[subject][id]. An undeclared type is the same 400 at filter[subject][type], and a value that isn't an object, or carries another member, is one at filter[subject].

It reads only the stored identifier, so it works on a linkage-only MorphTo declared cannotBeIncluded() and withoutRelatedEndpoint(). The relation must say where that identifier lives. A MorphTo declares identifiedByColumns(), and the Doctrine provider compares those two columns on the main query. A MorphToMany declares identifiedByRows(), and the filter is one correlated EXISTS over its through() entity. The in-memory provider compares the same fields through core's ArrayFilterHandler. A requested id matches a stored storage key or a stored wire id. A WhereMorph over a MorphTo identified only by an identifiedBy() closure fails cache:warmup on Doctrine, since a closure can't be compared in a query.

It works wherever a filter key does: a related endpoint, relatedQuery[<path>][filter] and a collection action's filters.

It follows the read rules of a filter through a relation for the type a request names: a target that type's scope hides never matches, and a type the caller may not read through the relation answers 403.

WhereHasMatching — the Doctrine escape hatch (not portable)

When the inner predicate is more than a single column comparison — a multi-column / OR / NOT condition, or raw DQL — reach for the bundle-only WhereHasMatching (haddowg\JsonApiBundle\DataProvider\Doctrine\Filter\). It is a single relationship hop whose related root you narrow yourself, with two surfaces:

use haddowg\JsonApiBundle\DataProvider\Doctrine\Filter\WhereHasMatching;
use Doctrine\Common\Collections\Criteria;

public function filters(): array
{
    return [
        // structured: apply a Criteria (AND/OR/NOT over the related entity) on the
        // related root, responding to filter[hitTracks]
        WhereHasMatching::criteria(
            'hitTracks',
            'tracks',
            Criteria::create()->where(Criteria::expr()->gt('plays', 100)),
        ),
        // raw hatch: a closure given the related-rooted subquery, the related
        // alias, and the request value — you add predicates and bind parameters
        WhereHasMatching::using('namedLike', 'tracks', static function ($sub, $alias, $value): void {
            $sub->andWhere("$alias.title LIKE :q")->setParameter('q', "%$value%");
        }),
    ];
}

Two boundaries set it apart from WhereThrough:

  • Doctrine-only. It lives in the Doctrine namespace and is recognised only by the Doctrine handler. On the in-memory provider the same filter[<key>] key is undeclared, so the request is a clean 400 (the unrecognised-filter boundary) — never a silent non-match.
  • Not value-validated. The author owns the request value (the closure consumes it, no declared operator compares it), so constraints() returns [] — there is nothing for the validator bridge to check.

Since only you know what the value means, tell clients with describedAs() and example(). Both return a copy, and the OpenAPI document shows them on the filter[<key>] parameter the way it does for core's value filters. The music-catalog example's artists declare one:

WhereHasMatching::using('albumTitle', 'albums', static function (QueryBuilder $albums, string $album, mixed $value): void {
    $albums->andWhere(\sprintf('LOWER(%s.title) LIKE :albumTitle', $album))
        ->setParameter('albumTitle', '%' . \mb_strtolower(\is_string($value) ? $value : '') . '%');
})
    ->describedAs('Only artists with an album whose title contains the value, ignoring case.')
    ->example('computer'),

WhereThrough, WhereThroughIn and WhereHasMatching share the one EXISTS builder in DoctrineFilterHandler; see doctrine.md for the DQL detail.

Pivot (belongsToMany) data

A belongsToMany relation can expose pivot (join-table) data: per-member values that live on the join, like a position ordering or an addedAt timestamp. Declare the pivot fields on the relation with fields() — as real field definitions, the same field DSL you use for attributes (Integer, Str, DateTime, …) with their constraints, casts and read-only / context behaviour:

BelongsToMany::make('tracks', 'tracks')
    ->fields(
        Integer::make('position')->required()->min(1),
        DateTime::make('addedAt')->readOnly(),   // server-owned, never written from meta
        Str::make('note')->maxLength(140),
    );

The fields() declaration drives pivot render, write / validate and sort. It renders each member's pivot values as meta.pivot on the related endpoint (GET /playlists/1/tracks), the relationship-linkage endpoint (GET /playlists/1/relationships/tracks), the 200 linkage a write to that endpoint answers with, which lists the members the relationship endpoint then serves, and in a primary-resource document's relationships block, wherever that relation's linkage data renders. It also makes ?sort=position recognised on that related endpoint (routed to the pivot column) — sorting is zero-config:

"data": [
  {
    "type": "tracks", "id": "7",
    "attributes": { "title": "Intro" },
    "meta": { "pivot": { "position": 1, "addedAt": "2024-01-01T00:00:00+00:00" } }
  }
]

Pivot rides every linkage that renders data. Whatever makes a pivot relation's linkage data render, each identifier carries its meta.pivot: an ?include, withData(), a relation whose value is already loaded on the model (a collection something else initialised, the members a write just set, or an extractUsing() relation the data layer can't see into), or a relation with no links to render instead (withoutLinks()). A lazy relation whose data stays out of the document renders links only, and no pivot is read for it. The pivot values are read once per include path for every parent at it, and only when a member's pivot renders. The related type's provider reads the stored values on every path, through PivotAwareProviderInterface. Doctrine reads them from the association entity; the in-memory provider keeps each pivot row beside its parent, writes it from every relationship write, create, update and atomic operation, and reads it back. A computed pivot field needs no storage, so both providers render it, on an all-computed and a mixed relation alike. A relation with stored pivot fields whose related type's provider doesn't implement PivotAwareProviderInterface fails the cache warm-up, naming the relation, the type, the provider and the interface.

The same holds wherever the parent renders, not only as the primary resource. A pivot relation reached through a nested include (GET /users/1?include=playlists.tracks, at any depth) carries meta.pivot on its linkage and on its included members, and so does one included from a related endpoint (GET /users/1/playlists?include=tracks), a MorphToMany related endpoint among them, in the response to a create or update, in a relationship write's 200 linkage, in an Atomic Operations result, or in a custom action's response, its 202 job resource included. The pivot map is read once per include path for every parent at it, never once per parent.

An included member is one resource object, so when two parents link to the same member with different pivot values, its meta.pivot in included holds one of them, and a member also reached through a path with no pivot may render without one. Each parent's linkage always carries that parent's own values, so read per-link pivot data from the linkage.

Each member's meta.pivot carries the pivot fields core's BelongsToMany::readablePivotFieldsFor($request, $member) returns: those neither hidden nor write-only for the request. A hidden(when:) predicate on a pivot field receives the related member (the track, not the join row), so it can hide a field on one member and show it on another. Every field it returns renders, null when the join row holds no value for it. A member the provider returns no pivot row for is a data integrity fault: the response fails with a logged 500 naming the type, the relation, the parent and member ids and the provider, and the error's debug meta says the same. A member whose every field is hidden for the request still carries "pivot": {}, and a relation that declares only an AdditionalProperties entry renders no pivot. That matches the response schema in the OpenAPI document, which requires meta.pivot on each member of a pivot relation's response linkage and lists its fields as required.

A DateTime pivot field follows the server's output_timezone like an attribute does: it renders in the server zone unless it sets its own outputTimezone(), and Date and Time pivot fields keep their value.

Filtering by a pivot column

Pivot filters are author-declared — distinct from sorts, which auto-derive. To expose a ?filter[…] over a pivot column, declare it on the relation's withFilters() as a normal core filter whose column is pivot.-prefixed. The pivot. prefix marks the filter as targeting the join: the bundle strips the prefix to the real pivot column (position) and routes the filter to the pivot alias. The filter key is independent of the column, so a pivot filter can be named anything:

BelongsToMany::make('tracks', 'tracks')
    ->fields(
        Integer::make('position')->required()->min(1),
        DateTime::make('addedAt')->readOnly(),
    )
    ->withFilters(
        Where::make('position', 'pivot.position'),           // filter[position]=2
        Where::make('positionGte', 'pivot.position', '>='),  // an operator
        WhereIn::make('positionIn', 'pivot.position'),        // filter[positionIn]=1,3
        Where::make('addedAfter', 'pivot.addedAt', '>'),     // a typed-date column
    );

Any core scalar-column filter works on a pivot column: Where and its operators, WhereIn/WhereNotIn, WhereNull/WhereNotNull. The value cast auto-resolves from the declared pivot field backing the stripped column — Integer coerces to int, DateTime to an ISO-8601 comparison — so a typed pivot column filters correctly with no extra wiring; an explicit ->deserializeUsing() on the filter still wins. A filter with no pivot. prefix targets the related entity, exactly like any relation-scoped filter.

The relationship filters can start from the pivot row too, through the associations its entity maps. A pivot. prefix on the relationship or path makes WhereHas, WhereDoesntHave, WhereThrough, WhereThroughIn and the bundle's WhereHasMatching test the row that links this parent to each member, not the member itself:

BelongsToMany::make('placeholders', 'placeholder-definitions')
    ->through(CampaignTemplatePlaceholder::class)
    ->fields(Str::make('defaultOverride')->nullable())
    ->withFilters(
        WhereDoesntHave::make('unused', 'pivot.targets'),            // filter[unused]: no target on this template's row
        WhereThrough::make('targetName', 'pivot.targets.name'),      // filter[targetName]=header
        WhereThroughIn::make('target', 'pivot.targets')->uuid(),     // filter[target]=<id>,<id>
    ),

GET /campaign-templates/7/placeholders?filter[unused] lists the definitions template 7 uses whose row on template 7 has no targets. A definition shared with another template where it does have targets is still unused here, which a filter on the definition itself can't express. A path that ends on one of the row's associations compares the id of the entity it reaches, bound with that id's Doctrine type. Its wire ids decode with the encoder of the type the relation names for that entity: the related type for the row's far side, the parent type for its near side. These filters apply where the pivot column filters do, and the in-memory provider, which doesn't query its pivot rows, rejects them with a 400 on every path, as it does the column ones.

A related type that declares a relation stored as pivot would make such a path ambiguous, so the cache warm-up fails naming the filter and the relation. Store that relation under another name with storedAs().

WhereThrough and WhereThroughIn are deprecated. Their pivot.-prefixed paths move to ->through() with a leading pivot segment, and the existence filters move with them:

->withFilters(
    WhereDoesntHave::make('unused', 'targets')->through('pivot'),
    Where::make('targetName', 'name')->through('pivot.targets'),
    WhereIdIn::make('target')->through('pivot.targets')->acceptsList(),
    Where::make('override', 'defaultOverride')->through('pivot'),  // a pivot field
)

The migrated filters apply on the same endpoints. Each association the path walks reaches a type: the registered type whose entity it targets, whose query extensions scope it, whose read rules gate it and whose encoder decodes its ids. The deprecated pivot.-prefixed forms reach the same types, so before and after migrating a filter hides the same rows and answers the same 403 to a caller who may not read a hop. The row's associations back to the parent and to the member reach the parent type and the relation's related type, even when another type serves the same entity. Every other association past pivot needs exactly one registered type for the entity it targets, in both forms. An entity no type serves, or several serve, has no type whose rules could apply, so a filter reaching it fails the cache warm-up in either form, naming the filter and its path. A pivot.-prefixed WhereHasMatching reaching one fails it too. Register one type for that entity, or move the filter to a ->through() path that doesn't reach it.

A filter family on the relation can resolve to a pivot filter too. The bundle resolves the family first and then treats what it returns as it treats an exact pivot filter: a pivot. column routes to the pivot alias and gets the field's cast wherever pivot filters apply, and where they don't its key is unrecognised just as the exact one is. The warm-up can't see the paths a family resolves, so a pivot.-prefixed path a family returns that reaches an entity no single registered type serves is refused when the request resolves it. The request answers 500 and the error log names the family, the filter and the path, since the declaration is at fault rather than the request.

Pivot filters apply wherever the Doctrine provider reads the relation through its pivot query: the related and relationship endpoints, a Relationship Queries relatedQuery[<relation>][filter] window on an include, and the ?withCount total that window reports. A provider with no pivot query, such as the in-memory one, leaves a pivot filter's key unrecognised, a 400.

->withFilters(
    FilterFamily::make('pin', fn(string $suffix, JsonApiRequestInterface $request): ?FilterInterface => match ($suffix) {
        'rank' => Where::make('pin.rank', 'pivot.rank')->build(),            // filter[pin.rank]=2
        'after' => Where::make('pin.after', 'pivot.pinnedAt', '>')->build(), // cast as a date
        default => null,
    }),
);

The documented value type does not come along for free. Core types an unconstrained filter's OpenAPI value from the single column it targets, and pivot. means nothing to it — the prefix is this bundle's convention, not core's — so a pivot filter with no declared constraint documents as the plain string every query parameter is on the wire, not as the integer or date its column really holds. Add the constraint you would add to any other filter (->integer(), ->numeric(), ->uuid(), …) and you get both: a 400 on a mistyped value and the narrower OpenAPI type.

A pivot field declared hidden() is filterable and sortable but never rendered: hidden() gates rendering only, never query. The field stays out of each member's meta.pivot, yet a pivot.-prefixed filter (and ?sort=) over its column still works — the filter reads the column on the join directly, not the rendered scalar. Use it for a join column you want to query by but not expose.

A pivot field declared writeOnly() is accepted in a write's meta.pivot and never rendered, the same rule a write-only attribute follows. A writeOnly(when:) predicate is evaluated against each request, and the field stays out of meta.pivot on every request it returns true for.

Filter / sort asymmetry. A pivot sort auto-derives from fields() — ?sort=position works with no further declaration. A pivot filter must be declared explicitly via withFilters() (a sort is a single well-defined ordering; a filter spans operators, sets and null checks the author must choose).

Migration (breaking change). Declaring a pivot field no longer auto-exposes a zero-config filter[<field>] equality. An app that relied on it must add the explicit declaration: ->withFilters(Where::make('position', 'pivot.position')). Pivot sorts are unaffected (still zero-config).

The Doctrine fact this rests on. A plain #[ORM\ManyToMany] join table holds only the two foreign keys — Doctrine cannot map a position/addedAt column on it. To HAVE pivot columns you must model the join as an association entity:

#[ORM\Entity]
class PlaylistTrack
{
    #[ORM\ManyToOne(targetEntity: Playlist::class, inversedBy: 'playlistTracks')]
    public ?Playlist $playlist = null;

    #[ORM\ManyToOne(targetEntity: Track::class)]
    public ?Track $track = null;

    #[ORM\Column(type: 'integer')]
    public int $position = 0;

    #[ORM\Column(type: 'datetime_immutable')]
    public ?\DateTimeImmutable $addedAt = null;
}

with the parent owning a OneToMany to it (Playlist -> playlistTracks -> PlaylistTrack) and the entity a ManyToOne to the far type (PlaylistTrack -> track -> Track). The Doctrine adapter auto-detects that association entity from your metadata (it finds the one to-many on the parent whose target also has a ManyToOne to the far type) and reads pivot render + filter + sort in one DQL query over it — correctly scoped, filtered, sorted and paginated, no extra round-trip. If auto-detection is ambiguous (two candidate association entities) or finds none, it throws a clear error pointing you at the override:

BelongsToMany::make('tracks', 'tracks')
    ->fields(Integer::make('position'))
    ->through(PlaylistTrack::class); // name the association entity explicitly

A type linked to itself

An association entity can link a type to itself, such as a seat placing one owner beside another. Its two ManyToOnes both target the owner, so the target class can't say which one points back at the parent. Name the sides in through():

#[ORM\Entity]
class Seat
{
    #[ORM\ManyToOne(targetEntity: Owner::class)]
    public ?Owner $owner = null;

    #[ORM\ManyToOne(targetEntity: Owner::class)]
    public ?Owner $peer = null;

    #[ORM\Column]
    public int $rank = 0;
}

BelongsToMany::make('peers', 'owners')
    ->through(Seat::class, parent: 'owner', related: 'peer')
    ->fields(Integer::make('rank')),
BelongsToMany::make('followers', 'owners')
    ->through(Seat::class, parent: 'peer', related: 'owner')
    ->fields(Integer::make('rank')),

parent: names the entity's ManyToOne pointing back at the parent and related: the one pointing at the member. Either can be left out when the other settles it. Each name must be a ManyToOne of the entity to the parent's entity or the related type's, or the cache warm-up fails naming the associations it could be.

A relation that names neither side can still be stored as the parent's OneToMany of the entity, mapped by its own side: ->storedAs('seats') on an owner whose #[ORM\OneToMany(targetEntity: Seat::class, mappedBy: 'owner')] $seats points at the owner association, which becomes the parent side.

A relation that declares through() reads its members through that entity's rows even when it declares no pivot field, as mates would with ->through(Seat::class, parent: 'owner', related: 'peer') and nothing else, and a write creates and removes those rows. Only a relation with a stored pivot field takes pivot.-prefixed filters and paths.

Reads, includes, counts, filters through the relation, pivot.-prefixed paths and writes all use these sides, and a write creates or removes only the parent's own rows. Any association entity whose sides are still ambiguous fails the cache warm-up, naming the relation, the entity and the candidate associations, and the through() that settles it, such as ->through(Seat::class, parent: 'owner'). That includes an entity with one association to the parent but several to the related type. An application with such an entity fails warm-up until the relation names the side.

Computed pivot fields

A pivot field declared with computed() or computedUsing() is computed: it has no column, its hook receives a core PivotEdge holding the parent and the related member of the link rather than a join row, and its value renders under meta.pivot like a stored one, through the field's own cast and the server's output_timezone.

BelongsToMany::make('members', 'users')
    ->fields(
        Str::make('role')->computedUsing(
            static fn(mixed $edge): string => $edge instanceof PivotEdge
                ? $edge->parent->roleOf($edge->related)
                : '',
        ),
    ),

A relation whose pivot fields are all computed needs no association entity. It is served over a plain #[ORM\ManyToMany] join table on Doctrine, and over the stored list on the in-memory provider, and both render its meta.pivot on the related endpoint, the relationship endpoint and a primary document's linkage. No through() is needed, and cache:warmup does not look for an association entity. A relation that mixes computed fields with stored ones still needs its association entity, as before, and reads the stored fields from it.

The in-memory provider renders a mixed relation's stored fields from the pivot rows it keeps beside each parent, a stored field with an extractUsing() hook included, and its computed fields beside them.

A computed pivot field is read-only. A write that sends it in the linkage meta is ignored, exactly like a read-only field, so a relation with only computed fields is replaced, added to and removed from like a plain to-many. It has no column, so it is neither a sort= key nor a field a pivot. filter casts through.

A stored pivot field with an extractUsing() hook is not computed. As on an attribute, the hook changes only how the field is read: it keeps its column on the association entity, stays writable from the linkage meta, and remains a sort= key and a pivot. filter column. Its hook receives the same PivotEdge, never the association entity, with the link's stored values under pivot, so it reads its own stored value from $edge->pivot['<name>']. Each value is in its wire form, the form the response renders, on every provider: a date is the string the field renders in the server's output zone:

BelongsToMany::make('crew', 'members')
    ->fields(
        Str::make('shift')->extractUsing(
            static fn(mixed $edge): ?string => $edge instanceof PivotEdge && \is_string($edge->pivot['shift'] ?? null)
                ? \strtoupper($edge->pivot['shift'])
                : null,
        ),
    ),

A serializeUsing() hook on a pivot field is not consulted; the stored value renders through the field's cast.

Writing pivot data

A pivot field is writable by default — settable from the linkage's resource-identifier meta (JSON:API allows a resource identifier to carry meta). Opt a server-owned column out with ->readOnly() (or ->readOnlyOnCreate() / ->readOnlyOnUpdate()); a read-only pivot field is never written from meta and takes its server value. The convention is the same on the relationship endpoints and inline in a whole-resource write:

// POST /playlists/1/relationships/tracks   — add a member with its pivot data
{ "data": [ { "type": "tracks", "id": "7", "meta": { "pivot": { "position": 3 } } } ] }

// PATCH /playlists/1/relationships/tracks  — full replacement = REORDER + sync
{ "data": [
  { "type": "tracks", "id": "9", "meta": { "pivot": { "position": 1 } } },
  { "type": "tracks", "id": "7", "meta": { "pivot": { "position": 2 } } }
] }

// PATCH /playlists  — the SAME linkage meta inline in a whole-resource write
{ "data": { "type": "playlists", "id": "1", "relationships": {
  "tracks": { "data": [ { "type": "tracks", "id": "7", "meta": { "pivot": { "position": 3 } } } ] }
} } }

The Doctrine adapter applies an association-entity diff: for each incoming member it upserts the join row — updating an existing row's writable pivot fields in place (the reorder), or creating a new row (the writable fields from meta, the read-only fields taking their server default). A PATCH (full replacement) also removes the rows whose member is no longer in the set; a POST adds/upserts the incoming and leaves the rest; a DELETE removes the incoming members' rows (a remove carries no pivot). Each member's meta is validated against the writable pivot fields' constraints, with a violation rendered as a 422 pointed at the linkage meta (/data/relationships/<rel>/data/<n>/meta/pivot/<field>, or /data/<n>/meta/pivot/<field> on the relationship endpoint). Because an add/replace may create a new association row for any incoming member — even on a PATCH — the meta is validated in the new-row (create) context, matching the persister (a new row is written in create context); a reorder of an existing row supplies the value, so this never wrongly rejects it. A read-only pivot field supplied in meta is ignored (it is not in the writable set, so it never raises and is never written — exactly how a read-only attribute is handled). A required writable pivot field absent when a new row is created is a 422 (at the linkage meta, before persist — never a database NOT-NULL 500), on the relationship-endpoint POST/PATCH and the whole-resource POST/PATCH alike.

Boundaries.

  • Querying is Doctrine-only. Filtering, sorting and paging by a pivot field needs an association entity to query. The in-memory provider keeps its pivot rows beside each parent and doesn't query them: a pivot ?filter/?sort key is unrecognised there (400), while a write stores the pivot fields each member sends and every response renders them in meta.pivot. A belongsToMany without fields() (and any HasMany) keeps the plain related-collection behaviour on both providers.
  • Scoped to the pivot relation's related endpoint. A pivot key is unrecognised on the primary /{relatedType} collection (400), exactly like a relation-scoped key.
  • One pivot row per member. meta.pivot is a single per-member value set, not a list. If the same member appears more than once (duplicate membership — a track at two positions), the collection returns one row per distinct member: the total is the distinct member count, no member splits across pages, and the rendered pivot values are a representative membership row. To render every membership, model the membership as its own resource instead.

See doctrine.md for the query, resolver and association-entity-diff detail.

Parent-aware identifier meta

meta.pivot is one automatic form of resource-identifier meta — the pivot columns of a belongsToMany. For any other per-link metadata, declare identifierMeta() on the relation: a resolver receiving (parent, related, request) whose result is merged onto each linkage identifier the relation renders — on a to-many member, a to-one's identifier, and the /{type}/{id}/relationships/{rel} endpoint. It is parent-aware (the pivot's far member sees only itself; this sees the owning model too) and so can describe the link rather than the resource:

HasMany::make('members', 'users')
    ->identifierMeta(fn(Team $team, User $member, $request): array => [
        'role' => $team->roleOf($member),
    ]),
GET /teams/1/relationships/members
  → data: [ { "type": "users", "id": "7", "meta": { "role": "captain" } }, … ]

The resolver runs identically on the in-memory and Doctrine providers — it reads the related objects the provider already loaded for the linkage, so it needs no data-layer support. It composes with meta.pivot (both ride the identifier's meta, the resolver winning on a key collision) and is linkage-only — the resource expanded into included is untouched. The hook itself is core; see core relations.md for the full reference.

Pass fields: to describe what the resolver returns, and the served OpenAPI document types each linkage identifier's meta with those members instead of leaving it open:

HasMany::make('members', 'users')
    ->identifierMeta(
        fn(Team $team, User $member, $request): array => ['role' => $team->roleOf($member)],
        fields: [Str::make('role')->guaranteed()],
    ),

The relation gets a <Type><Rel>IdentifierMeta component, and on a belongsToMany it sits beside pivot in the same meta. The fields only describe the shape: the resolver still produces the values, so return them in their wire form. They are read-only, so a write never sends them, and a member named pivot is refused.

Relationship mutation

The bundle serves PATCH/POST/DELETE …/relationships/{rel} over the CrudOperationHandler. Core owns the mutation model — request-shape validation (cardinality → 400, mutability flags → 403) and the typed exceptions (core relationship-mutation). The bundle owns the storage-correct apply: it loads the parent, resolves the named relation, guards mutability, parses the linkage with core's body parser, then calls the persister's DataPersister::mutateRelationship() seam (the six-arg signature lives in data-layer.md).

The change is applied inside the persister's transaction. Before it commits, the changed parent runs through the resource's entity-level constraints in the update context, and a violation is a 422 that rolls the change back.

Before the persister runs, the linkage's resource type is checked against the relation's declared related type(s). A { "type": T, "id": X } whose T is not an accepted inverse type — a BelongsTo::make('author', 'authors') sent a { "type": "comments" } linkage — is a 409 Conflict (RESOURCE_TYPE_UNACCEPTABLE), the linkage twin of the resource-type conflict core already returns for a POST /{type} whose data.type does not match the endpoint. A polymorphic relation (MorphTo::make('pinned', ['notes', 'images'])) accepts any of its declared types. The same check covers a relationship embedded in a whole-resource write (the error then points at /data/relationships/{rel}/data/type). The check runs on every write path, Atomic Operations included, whether or not symfony/validator is installed. This is distinct from the cardinality guard (a to-one sent an array → 400), which is about the linkage shape, not the resource type of its identifiers. A resource object whose attributes, relationships or meta is present but not an object is a 400 (REQUEST_BODY_INVALID_JSON_API, pointing at the member) before any of it is applied.

The persister resolves each identifier id under that identifier's own type to the actual related objects/references — the Doctrine reference to a managed reference + FK write, the in-memory provider to the stored object via its $relatedResolver. An empty linkage clears the relationship. The same seam is reused for relationships embedded in whole-resource writes (a data.relationships member on a POST/PATCH /{type} — applied with flush: false so the single create()/update() owns the commit).

The RelationshipMutationTest exercises the full matrix over Doctrine, re-reading after clearing the identity map so the assertion proves the change reached the database:

PATCH /tracks/1/relationships/album   {"data":{"type":"albums","id":"2"}}  → 200, replaced
PATCH /tracks/1/relationships/album   {"data":null}                        → 200, cleared
POST  /tracks/3/relationships/playlists {"data":[{…}]}                     → 200, added (idempotent)
DELETE /tracks/1/relationships/playlists {"data":[{…}]}                    → 200, removed

A whole-resource write threads the same path — a favorites create carrying a to-one user in data.relationships writes the FK, and a tracks PATCH carrying album replaces the association.

Note: a data.relationships member on a create/update is not hydrated by core onto a typed association property — the bundle strips it before core hydrates id+attributes, then applies each relationship through mutateRelationship(... Mode::Replace, flush: false). See data-layer.md.

Relations written by fillUsing()

A relation that declares fillUsing() is written by that hook, never by the persister. Use it when the relation is not a plain association, such as a MorphTo stored as a type column and an id column:

MorphTo::make('target', ['advertisers', 'agencies'])
    ->identifiedBy(static fn(mixed $file): ?array => $file instanceof File && $file->targetId !== null
        ? [$file->targetType, $file->targetId]
        : null)
    ->fillUsing(static function (File $file, ToOneRelationship $linkage): File {
        $file->targetType = $linkage->resourceIdentifier?->type;
        $file->targetId = $linkage->resourceIdentifier?->id;

        return $file;
    }),

The hook runs on a create, an update, the relationship endpoints and Atomic Operations, with the arguments core's own hydration passes. A whole-resource write calls it with an empty $data array. The relationship endpoints pass a to-many's mode as $data['mode'], so a POST adds and a DELETE removes. Everything else around the write still applies. The linkage is checked against the related types' providers before the hook runs, so an id no row holds or the caller can't see is a 404. The mutability and update gates run before and after the hook, and the persister then saves the parent, so a refusal after the hook rolls the write back.

Request-aware mutation guards

The cannotReplace()/cannotAdd()/cannotRemove() flags also accept a closure, making the 403 a per-caller decision rather than a blanket lock:

HasMany::make('medals', 'medals')
    ->cannotReplace(static fn(mixed $model, JsonApiRequestInterface $request): bool
        => $request->getHeaderLine('X-Role') !== 'admin')

The closure returns true when the restriction applies (cannot replace), so a non-admin PATCH …/relationships/medals is FullReplacementProhibited (403) while an admin's succeeds; cannotAdd/cannotRemove gate POST/DELETE the same way. The handler resolves each gate against the inbound request and the loaded parent (allows*For($request, $parent)), and the same request-aware read-only gate applies to a relation embedded in a whole-resource write (a readOnly(fn) relation is skipped only for the callers it is read-only for). This is the relationship arm of the per-caller predicate family.

The replacement gate on embedded whole-resource writes

A relationship embedded in a data.relationships member of a whole-resource write is applied as a full replacement of that association (an embedded write is always the complete set, never an incremental add or remove). So on a whole-resource PATCH the handler enforces cannotReplace() on each embedded relation exactly as it does at the dedicated endpoint — a non-admin PATCH /badges/1 whose body embeds the gated medals relation is FullReplacementProhibited (403), not a silent replacement. The gate runs before the persister applies, so nothing is mutated.

The gate is skipped on a POST (create): a create sets the relationship's initial state — there is nothing to replace — and gating it would make a cannotReplace relation impossible to ever set, since such a relation has no relationship endpoint either. So a guest may POST /badges with the gated medals embedded; only a replacement of an existing relationship is gated.

cannotAdd()/cannotRemove() have no embedded analogue: an embedded write is always a full set, never an incremental POST-add or DELETE-remove, so those two gates apply only at the …/relationships/{rel} endpoint.

Fixed membership

A to-many declared with core's cannotChangeMembership() keeps the members it has. A replacement may restate them in any order, with repeats, but it must name exactly the current members, compared by type and id; a member sent with only a lid counts as new. Anything else is 403 MEMBERSHIP_CHANGE_PROHIBITED at /data/relationships/{rel}:

HasMany::make('tracks', 'tracks')->cannotChangeMembership(),

The handler checks it on a PATCH …/relationships/{rel}, on the relation embedded in a whole-resource PATCH and on both inside Atomic Operations, where the pointer gains the operation's prefix. A create sets the members freely. The relation can't grow or shrink, so a POST or DELETE on its relationship endpoint is ADDITION_PROHIBITED or REMOVAL_PROHIBITED, and the OpenAPI document lists only GET and PATCH for it. A closure, cannotChangeMembership(fn($model, $request) => …), fixes the members only for the requests it returns true for, and the document keeps every verb.

The current members are read off the loaded parent the way the relationship linkage renders them, so the check works the same on every data layer: an identified MorphToMany reads its stored pairs, and a pivot belongsToMany reads the far members of its association entity rows, as its linkage does, whether or not it declares an extractUsing(). Any other relation reads its value (a Doctrine collection, or a fillUsing() relation's read side) with each member's id as its serializer writes it. The check runs on the linkage after the scope is applied, which keeps the members the scope hides, so a caller lists exactly the members it can see; naming one it can't see is the usual 404. The bundle writes every association itself, so this is the only membership check a request goes through.

Per-relation endpoint exposure

A relation can suppress individual endpoints. The exposure flags themselves are core (RelationInterface), but the bundle enforces them handler-side — the relationship routes stay parametric (one route per shape, emitted once per type), so suppression cannot live in routing. The handler maps each flag to a JSON:API error, and core already omits the convention link to a suppressed endpoint, so a rendered self/related link never points at a 404:

Flag (core, on the relation) Request affected Bundle result
withoutRelatedEndpoint() GET /{type}/{id}/{rel} 404 RELATIONSHIP_NOT_EXISTS
withoutRelationshipEndpoint() GET/mutate …/relationships/{rel} 404 RELATIONSHIP_NOT_EXISTS
cannotAdd() POST …/relationships/{rel} 403 ADDITION_PROHIBITED
cannotReplace() PATCH …/relationships/{rel} 403 FULL_REPLACEMENT_PROHIBITED
cannotRemove() DELETE / to-one clear 403 REMOVAL_PROHIBITED
cannotChangeMembership() PATCH that changes the members; POST/DELETE 403 MEMBERSHIP_CHANGE_PROHIBITED; ADDITION_PROHIBITED/REMOVAL_PROHIBITED
readOnly() / readOnlyOnUpdate() PATCH/POST/DELETE …/relationships/{rel} 403, the code for the verb

The enforcement is in CrudOperationHandler::guardMutability(). TrackResource's playlists declares cannotReplace(), so a full PATCH replacement of that to-many is a 403 and the existing set is untouched — witnessed by RelationshipMutationTest::patchingACannotReplaceToManyIsForbidden. A cardinality mismatch (a POST/DELETE against a to-one) is a separate 400 RELATIONSHIP_TYPE_INAPPROPRIATE; an unknown relation or missing parent is a 404.

A relationship mutation is an update of the parent, so a relation that is read-only on update refuses all three verbs with the code that matches each one. When it is unconditionally read-only, the OpenAPI document lists only the relationship GET for it and leaves it out of the update request body; a readOnly(fn) predicate is judged per request, so the document keeps the mutations.

Hidden relations

hidden() keeps a relation out of every response. hidden(fn(mixed $model, JsonApiRequestInterface $request): bool => …) decides per parent and request. When the predicate holds, the relation is left out of the resource, and its related and relationship GETs answer 404 (RELATIONSHIP_NOT_EXISTS), the same as an undeclared relation. The handler checks this before the read gate, so a caller the parent's gate would refuse also gets the 404. The mutation endpoints still find the relation and keep their own 403s.

Write-only relations

A relation declared writeOnly() is accepted on a write and never shown on a read. Core leaves it out of every response's relationships, rejects it in ?include and ?withCount, answers its related and relationship GETs with 404, and answers its relationship mutations with 204. The bundle follows that on its own read paths:

  • a read never loads it. The include preloader, the Relationship Queries window, the ?withCount batch and the pivot meta batch all skip it, so a withData() write-only to-many costs no query;
  • relatedQuery[<rel>] (or rQ[<rel>]) naming it is the same 400 QUERY_PARAM_UNRECOGNIZED an unknown relation gets;
  • the OpenAPI document drops it from the read schema and documents no related endpoint or relationship GET for it, keeping the create/update schemas and the mutation operations.

writeOnly(fn) is judged per request, so the read paths skip the relation whenever the predicate holds for that request. The OpenAPI document describes the superset and keeps documenting reads of a predicate-gated relation, as it does for a predicate-gated attribute.

GET /albums/1/artist returns an artists resource object as primary data, so the server serving it needs a serializer for artists and the OpenAPI document needs its field inventory. A relation that exposes its related endpoint to a type the server does not register is therefore a configuration error, and cache:warmup fails the build over it (the OpenAPI export refuses too, whichever runs first). Three ways out:

  • register the related type on that server as well;
  • point the relation at a reduced second type that is registered — the example does this with public-profiles beside the admin-only users, both backed by the same User entity;
  • declare the relation linkage-only with withoutRelatedEndpoint(). The linkage {"type": "users", "id": "1"} asserts no shape, so an unregistered target is fine there; the related link is omitted so nothing points at the 404.

A type reached only as linkage never needs registering. It is exposing the endpoint that makes the claim.

The OpenAPI examples build linkage from the related type's Id example, which an unregistered type can't give. Declare the id on the relation with exampleId(), as the example's playlists.owner does:

BelongsTo::make('owner', 'users')
    ->withoutRelatedEndpoint()
    ->exampleId('1'),

Without it, a read shows that relation's links and no data, a write leaves it out, and the relationship endpoints get no example. The related type's own example still wins wherever the server registers it.

Controlling what can be included

?include is a compound-document amplifier — a deeply nested path or a default-include cascade can walk the relationship graph without bound, and a default-include pointing back at its own type (or a mutual pair) loops the renderer forever. Four composing include safeguards bound it. All four live in core (an opt-in IncludeControlsInterface the transformer reads via instanceof, plus a relation-level wither); the bundle supplies the opinionated depth default and makes the built-in include batcher respect them.

Safeguard Where declared Effect
A — per-relation opt-out cannotBeIncluded() on the relation, or cannotBeIncluded(fn($model, $request)) to decide per request A ?include naming it is a 400 INCLUSION_NOT_ALLOWED at any path, and it is excluded from the default-include cascade. The closure form runs as each resource renders, so it only applies to requests that render the relation, and the OpenAPI document still lists the path.
B — max include depth json_api.max_include_depth (default 3), overridable per resource via IncludeControlsInterface::maxIncludeDepth() A ?include deeper than the effective cap is a 400 INCLUSION_DEPTH_EXCEEDED; a default cascade stops at the cap (so a mutual default-include cycle terminates).
C — allowed include paths IncludeControlsInterface::getAllowedIncludePaths() on the root resource A list of the full dotted paths a client may request when this resource is the request's root (a listed deep path implies its ancestors); any requested path neither listed nor an ancestor of one is a 400 INCLUSION_NOT_ALLOWED. null is unrestricted; [] permits no includes.
D — excluded include paths IncludeControlsInterface::getExcludedIncludePaths() on the root resource A list of the full dotted paths a client may not request when this resource is the root. An excluded path also refuses everything below it, so excluding author refuses author.company. A request for one is a 400 INCLUSION_NOT_ALLOWED. The default [] excludes nothing.

They compose: a requested path is permitted only if every hop's relation is includable (A), it is within the effective max depth (B), when the root sets a whitelist it is a member of that list (C), and it is not at or below one of the root's excluded paths (D).

A relation marks itself non-includable like any other flag:

// A back-reference whose only purpose is reverse navigation, not compounding:
BelongsTo::make('parent', 'categories')->cannotBeIncluded();

Capability A is all-or-nothing for a relation at its own level — it cannot say "comments is includable on posts directly (GET /posts?include=comments) but NOT when reached from a parent (GET /users?include=posts.comments)". Capability C closes exactly that gap: it is evaluated once against the request's root resource and governs the whole nested tree, so it can forbid a nested path even where the relation is includable from its own root:

final class UserResource extends AbstractResource
{
    // Reading a user may compound their posts and each post's author, but never a
    // post's comments — even though `comments` is freely includable on `posts`.
    public function getAllowedIncludePaths(): ?array
    {
        return ['posts.author'];
    }
}

A listed deep path implies its ancestors, so ['posts.author'] permits both posts and posts.author without enumerating every prefix; only the unlisted sibling posts.comments is rejected.

When nearly everything should stay includable, Capability D is the shorter way to write it. List only the paths to refuse:

final class UserResource extends AbstractResource
{
    // Everything stays includable except a post's comments and anything below them.
    public function getExcludedIncludePaths(): array
    {
        return ['posts.comments'];
    }
}

posts and posts.author still work, while posts.comments and posts.comments.author are both rejected. Declaring C and D together lets a resource allow a deep tree and carve one branch out of it. Both lists take plain dotted paths with no wildcards, and both check only the paths a client requests: a relation included by default still renders, so use cannotBeIncluded() to stop that. The generated OpenAPI document leaves excluded paths out of the include parameter.

The include parameter in the generated OpenAPI document follows relation loops within the depth cap. It walks into the same type at most twice after the root, and lists the hop after that without walking it. A runs type with a retryOf relation back to runs lists retryOf, retryOf.retryOf and retryOf.startedBy under a cap of 2, and a self-referencing friends lists friends.friends.friends but nothing deeper, however high the cap. Each relation back to the same type multiplies the list, so for a type with several of them, or a loop between two types, exclude the paths clients don't need with getExcludedIncludePaths() or lower maxIncludeDepth() to keep the enum small.

max_include_depth is the one config-driven safeguard — see configuration → max_include_depth for the cap, the per-resource override, and how it terminates a default-include cycle. The built-in include batcher (no extra dependency; see doctrine → eager-loading includes) honours all three: it never batch-loads a non-includable relation, bounds its own recursion by the same effective depth, and skips a path the root's whitelist excludes (so a mutual default-include cycle terminates the batcher too, not only the renderer).

Whatever a document renders for a relation, it renders what the related endpoint serves. That covers included resources at every depth, the linkage data of a relationship whether or not it is included (a withData() relation, a collection your code already loaded, a to-one), pivot meta.pivot, ?withCount totals, the Relationship Queries window, on() attributes flattened through a to-one, and the to-one related and relationship endpoints. A Doctrine query extension or a provider that hides rows hides them from all of these, on every server. So does a filter default of the related type or of the relation: an included or always-emitted to-many lists only the members the related endpoint serves with no filter sent, which is the set ?withCount counts. A default the relation drops with withoutFilterDefaults() narrows none of them.

The members are loaded before the document renders. A lazy to-many into a scoped or default-filtered type, or one with a default read order, that wasn't loaded then renders links and no data, even if an attribute or a hook initialises its collection afterwards. Declare it withData() or include it to render its linkage.

The bundle reads a relation through the provider that serves its related endpoint (the provider of its first related type). When that provider scopes its reads and is not the parent type's provider, each parent's members are fetched through it, as the related endpoint does. The loaded members, or a to-one's target, reach the renderer through core's out-of-band linkage seams, so nothing is written onto the entity. A to-one whose target the scope hides renders data: null, is left out of included, flattens to null through an on() attribute, and a write to such an attribute is a 422 RELATED_ATTRIBUTE_OWNER_MISSING. A MorphTo target is checked against the provider of the type it renders as.

A relation with extractUsing() gets its candidates from the closure, and when its related type is scoped the scope still decides which of them exist: the bundle keeps only the rows the related type's provider admits, before any filter, sort or page runs, so linkage, included, both endpoints, ?withCount, the Relationship Queries window and on() through a to-one all show the narrowed set and every count matches it. The Doctrine provider admits rows with one WHERE id IN (…) query per relation per level, with its extensions applied; a custom provider can do the same by implementing AdmitsRowsInterface, and is otherwise asked through fetchOne() one row at a time. When the related type isn't scoped, linkage and included render the closure's value as it is, at no extra cost, and both endpoints and ?withCount page and count that value in memory. The provider is never asked to query the relation, so a computed polymorphic to-many works on the Doctrine provider without a custom one. A pivot belongsToMany always loads through the provider's pivot query.

A relation stored on a getter or property that is not a Doctrine association renders what the model returns; your code owns its scoping.

A polymorphic to-many is scoped when any of its member types is. Its members are grouped by type and the rows of each scoped type are kept only when that type's provider admits them, with the same probe, before any page, sort or count, so linkage, included, both related endpoints and ?withCount show the narrowed set with full pages and exact totals. Rows of an unscoped type cost nothing extra.

An association the provider cannot batch, such as one with a composite-key target, is refused with a 500 (a \LogicException naming the relation) rather than rendered from the model.

A provider tells the bundle whether its related reads are scoped by implementing ScopesRelatedReadsInterface. The Doctrine provider reports a relation scoped when any query extension supports one of its related types; the in-memory provider never does.

Every relationship write checks its linkage before anything is stored: data.relationships in a create or update, the …/relationships/{rel} endpoints, and atomic operations (after their lids resolve). Each identifier must be a row its type's provider serves, as GET /{type}/{id} would serve it, whichever persister then applies the write. A MorphTo or MorphToMany identifier is checked against the type it names. The check asks each type once per write, through FetchesByIdsInterface or AdmitsIdsInterface when the provider implements either, and through fetchOne() when it implements neither or for an id the batch left out. A type no provider serves has nothing to check against. An identifier the provider does not return, because no row holds it or because a scoped type's scope hides it, gets the response JSON:API prescribes for a related resource that does not exist:

{"errors": [{"status": "404", "code": "RESOURCE_NOT_FOUND", "title": "Resource not found"}]}

That holds for adding, replacing and removing members, for setting a to-one, and for a pivot member's meta.pivot (a hidden member's pivot also validates as a new member's). Removing an existing resource that isn't a member changes nothing. In an atomic batch the error rolls the whole batch back.

A to-many replace (a PATCH to the relationship endpoint, or the relationship in a resource body) changes only the members the client can see. Members the scope hides stay, with their pivot rows, and the response lists only the visible members:

advertiser 1 partners: agencies 1, 2 (agency 2 hidden)
PATCH /advertisers/1/relationships/partners {"data":[{"type":"agencies","id":"3"}]}
→ 200 {"data":[{"type":"agencies","id":"3"}]}, stored: agencies 2, 3

A to-one has one slot, so a client allowed to write it replaces, or clears, whatever it holds. A create also scopes the on() hops below the relations its body sets, so writing a flattened attribute through a hidden target is a 422 RELATED_ATTRIBUTE_OWNER_MISSING, as on an update.

A polymorphic relation checks each id against its own type's provider, so a hidden or missing id is a 404 and a replace keeps the hidden current members attached, as above.

Polymorphic relationships

A MorphTo to-one and a MorphToMany to-many point across several related types, so the member's serializer is resolved per-object rather than from a single declared type. Core's PolymorphicSerializer and per-object resolution own the rendering (core related-endpoints); the bundle wires the data path and splits responsibility between the two providers.

A MorphTo or MorphToMany is polymorphic however many types it lists. MorphTo::make('writer', ['authors']) is not a BelongsTo. Its endpoints take none of authors' filters, and relatedQuery[writer] is refused. A single-type MorphToMany likewise takes none of its type's filters or sorts, and its relationship endpoint takes no page. Each is a 400, exactly as for a relation over several types. The OpenAPI document projects it as a one-member union and advertises the same parameters, so adding a second type later changes neither the document's shapes nor what a request may send. The members still load as one query while there is one type, so the Doctrine provider serves a single-type MorphToMany without a custom provider.

The documented include enum follows the same rule. It lists writer but no path through it, so writer.agency is not in the parent's enum and GET /{type}/{id}/writer documents no include parameter, as for a relation over several types. A request may still send those includes. While there is one type the server knows the vocabulary, so ?include=writer.agency and GET /{type}/{id}/writer?include=agency still work.

Polymorphic to-one (MorphTo)

FavoriteResource declares favoritable over three types:

MorphTo::make('favoritable', ['tracks', 'albums', 'artists'])
    ->identifiedByColumns(type: 'targetType', id: 'targetId')
    ->extractUsing(static fn(mixed $favorite): ?object => $favorite instanceof Favorite ? $favorite->favoritable : null),

The linkage renders from the stored targetType/targetId pair, as described below, and the related object is read through extractUsing() when the target itself renders. The handler resolves the to-one serializer from the actual related object, so the same relation renders an albums resource for one favorite and an artists resource for another, and an empty target renders data: null. Because the target spans entity classes, the Doctrine read leaves the non-mapped property null; a thin custom provider — FavoriteProvider — delegates the fetch to the Doctrine provider, then fills $favoritable from the entity's stored targetType/targetId pair across per-type repositories (sharing the EntityManager, so the member comes back managed). The PolymorphicTest witnesses GET /favorites/1/favoritable → a tracks member, /favorites/2/… → an albums member, /favorites/3/… → an artists member.

A MorphTo stored as a type and id pair

When the parent stores its target as two plain columns, declare identifiedBy() and the linkage renders straight from the pair, without loading the target. The pair is [$type, $id], with $type one of the declared types and $id the stored key, or null for an empty relation:

#[ORM\Entity]
class Campaign
{
    #[ORM\Column(nullable: true)]
    public ?string $targetType = null;

    #[ORM\Column(nullable: true)]
    public ?int $targetId = null;
}

MorphTo::make('target', ['advertisers', 'agencies'])
    ->identifiedBy(static fn(mixed $campaign): ?array => $campaign instanceof Campaign && $campaign->targetId !== null
        ? [$campaign->targetType, $campaign->targetId]
        : null),

When nothing can hide a target, a page of campaigns renders every target linkage from the one campaign query. A target type is guarded on a server when its provider may hide a row, such as a Doctrine type with a query extension or a custom provider that scopes, when the type declares a read gate (securityRead, or security), or when the relation declares its own security(read:). A pair naming a guarded type loads its target before the linkage renders: one query per guarded type for the whole page, through that type's provider. A target the scope hides, the read gate refuses or that no longer exists then renders as data: null, as for any guarded to-one. Pairs naming an unguarded type still render as stored, without a load, so a missing row of an unguarded type keeps its pair. GET /campaigns/{id}/relationships/target follows the same rule.

?include=target loads every type's targets the same way, one query per type, and a row that doesn't come back renders as data: null and stays out of included. Includes beneath the target, such as target.region, follow the usual walk. GET /campaigns/{id}/target loads the one target and renders data: null when it is hidden or missing. A stored type the relation doesn't declare throws a \LogicException, which renders as a 500.

When the pair lives in two fields of the entity, as here, name them instead of writing a closure, and the linkage renders from them the same way:

MorphTo::make('target', ['advertisers', 'agencies'])
    ->identifiedByColumns(type: 'targetType', id: 'targetId'),

A typeMap maps stored values to types when the column holds something other than the JSON:API type, as identifiedByRows() does. Declared this way the columns can be compared in a query, which a WhereMorph filter needs. The example's FavoriteResource declares its favoritable relation this way and filters by it with filter[favoritable][type]=albums&filter[favoritable][id]=1.

The id column may hold the target's storage key or its wire id. They differ only when the target's type declares an id encoder, and a text column that holds the ids of several kinds of target often keeps the wire form. The linkage, the related endpoint, the include and WhereMorph accept either, and so do a MorphToMany's link rows. Link rows the bundle writes hold the storage key.

The id field may also hydrate to a value object, as a uuid column gives a Uuid. Its string form is the stored id, so the linkage renders without a getter that returns a string, and WhereMorph binds a requested id through the column's own type. A uuid a text column keeps in capitals renders in lower case, as the target does, and the related endpoint, the include and WhereMorph match it. The column is compared as stored, with the lower-case and upper-case forms bound, so an index on it still serves the query, and a column that mixes case within one id doesn't match.

The same two fields let each target type read its rows back with a HasMany or HasOne that names the MorphTo as its foreign key, as a foreign key through a polymorphic relation describes.

A loaded target renders under the pair's type, and the read gate, the related endpoint and the include walk all treat it as that type. The declared types' resources don't need to override getType(), so one entity class can back several of them. The build check that requires a class-discriminating getType() applies only to a MorphTo without a stored pair. A provider that loads the targets for you implements FetchesByIdsInterface (see custom providers → loading many rows by id). Writes still go through fillUsing(), shown below in relations written by fillUsing().

Polymorphic to-many (MorphToMany)

LibraryResource declares MorphToMany::make('items', ['tracks', 'albums', 'artists']) — a mixed collection. The provider responsibilities differ by storage:

  • The in-memory provider supports it: it reads the mixed collection off the parent and slices with page. A polymorphic to-many carries no shared filter/sort vocabulary, so filter/sort are a 400 while page windows.
  • The Doctrine provider throws "unsupported" for a to-many over several types — members span entity classes, so no single scoped query can fetch them. Declare it with identifiedBy() when the parent stores type and id pairs (see below), compute it with extractUsing(), or supply a custom provider (→ custom-data-providers.md).

The example app demonstrates the escape hatch with LibraryItemsProvider, which resolves the mixed libraries.items members across their per-type repositories. It registers for two types so every entry point sees the same members: for libraries it delegates the parent fetch to Doctrine then populates the non-mapped Library::$items (so the linkage endpoint and ?include read the mixed list off the parent), and for tracks it answers fetchRelatedCollection() (the related-collection dispatch resolves a provider by the relation's first declared type). The members render through a PolymorphicSerializer that discriminates each by its own type. PolymorphicTest witnesses GET /libraries/1/items → [tracks:1, albums:2, artists:1], the matching linkage endpoint, and ?include=items yielding the three mixed included resources.

A MorphToMany stored as type and id rows

When the members are join rows that each name a type and an id, declare identifiedBy() on the MorphToMany and return the parent's pairs in order:

#[ORM\Entity]
class UserCompany
{
    #[ORM\ManyToOne(inversedBy: 'userCompanies')]
    public User $user;

    #[ORM\Column]
    public string $companyType;

    #[ORM\Column]
    public int $companyId;
}

MorphToMany::make('companies', ['agencies', 'advertisers', 'publishers'])
    ->countable()
    ->identifiedBy(static fn(mixed $user): array => $user instanceof User
        ? array_map(static fn(UserCompany $row): array => [$row->companyType, $row->companyId], $user->userCompanies->toArray())
        : [])
    ->fillUsing($writeTheJoinRows),

The linkage renders from the pairs in their order. A member type is guarded when its provider may hide a row: a Doctrine type with a query extension, or a provider that scopes. Each guarded type is checked once for the whole page with an id-only query, and a hidden or missing member is left out of the linkage. Pairs naming an unguarded type render as stored, with no query. A per-row read gate doesn't guard a type here, since a to-many's rows are never gated one by one.

Every read that counts or pages the members works from the pairs. It checks each guarded type once over all of the parent's pairs before anything else, so a page is never short and a total is exact:

  • GET /users/{id}/companies cuts the page from the admitted pairs, in pair order, and loads only that page's rows, one id IN (...) per type. filter and sort are a 400 unless the relation declares pivot fields, and ?withCount=_self_ counts the admitted pairs.
  • ?withCount=companies on a user or a collection counts the admitted pairs.
  • ?include=companies loads every member's row, one query per type, and leaves a row that doesn't come back out of both the linkage and included.
  • GET /users/{id}/relationships/companies pages the admitted pairs exactly as the related endpoint does, with the same paginator, page parameters and ?withCount=_self_, but loads no rows. filter and sort are a 400 unless the relation declares pivot fields. Other polymorphic to-many relationship endpoints still refuse page too.

The pairs must point at rows that exist. A guarded type checks every pair, so a pair whose row is gone drops out and pages and totals stay exact. An unguarded type costs no query, so a dangling pair of one still shows in the linkage, and a related page that reaches it comes back one member short.

Each member renders under its pair's type, so one entity class can back several of the types without overriding getType(). A stored type the relation doesn't declare throws a \LogicException, which renders as a 500. Writes go through fillUsing(), and a replace keeps the members the scope hides, as for any scoped to-many. A provider that can answer the id-only check without loading rows implements AdmitsIdsInterface (see custom providers → loading many rows by id).

When each member is a row with an owner, a stored type and an id, declare those fields instead of a closure, and the data layer queries and writes the rows itself:

MorphToMany::make('companies', ['agencies', 'advertisers', 'publishers'])
    ->storedAs('userCompanies')
    ->through(UserCompany::class)
    ->identifiedByRows(owner: 'user', type: 'companyType', id: 'companyId')
    ->fields(Integer::make('rank')->required(), Str::make('note'))
    ->withFilters(Where::make('minRank', 'pivot.rank', '>='))
    ->defaultSort(new SortDirective(SortByField::make('rank'), descending: false)),

The fields are properties of the through() entity. A stored type is the member's JSON:API type unless a typeMap maps stored values to types. The owner field must identify exactly one owning type: the rows are read by that field alone, with no owner type beside it, so a link table shared by several owner types isn't supported yet. The id field may be of any mapped type, a uuid included, and is compared through it. A row whose type names no declared type, or that has no id, isn't a member, and members read by the request's sort, else the relation's default order, ties broken by stored type then id.

On Doctrine the relationship and related endpoints read a page in one query on the through() entity: the rows whose owner is the parent and whose type counts, filtered and sorted on the row's own fields, ordered by the tiebreak and cut to the page. A guarded member type is narrowed in the same query to the ids its provider admits, so a page is never short and a total is exact. Which ids those are takes one key-only read of the entity for every parent being rendered, the owner, type and id fields alone, and one admission query per guarded type across all of them, the linkage of a whole page of parents included. That linkage reads every parent's rows in one query over the owner field, so a page renders it in one row read plus that key read and admission. A custom provider reads a page's rows by implementing ReadsLinkRowsInterface. The page's members then load one id IN (...) per type. The in-memory provider runs core's InMemoryLinkRows over the rows the parent holds, with the same rules.

A relation declared this way takes no fillUsing(); declaring one fails the build. Core plans every write as a LinkRowWritePlan and the persister applies it: the rows to delete, then the rows that move to a temporary position, then the updated rows, then a new through() entity for each added member, its owner set through the association and each value converted to its column's form. Doctrine flushes after each pass inside the write's transaction. A replace keeps the members the scope hides, after the members the client sent, in their current order. As on every relation, each member a write names is checked against its type's provider first. A custom persister applies plans by implementing WritesLinkRowsInterface, and a custom provider serves the key read by implementing core's LinkRowKeysInterface.

The link rows can carry fields of their own, declared with the same fields() and withFilters() a pivot belongsToMany uses. Each linkage identifier renders the readable fields as meta.pivot, and on the related endpoint each member's resource object carries the same meta.pivot. Both endpoints take sort by any stored pivot field and filter by a pivot.-prefixed filter, run over the link rows, and nothing else, since the members share no other vocabulary. A default read order may name a pivot field and orders the linkage too.

A write sends the writable fields in meta.pivot, validated like a belongsToMany's: a new member in the create context, a member already present merged over its stored values in the update context. A relation declared with identifiedByRows() writes them through its plan.

A relation read through an identifiedBy() closure can declare pivot fields too, by returning each member as a [$type, $id, $row] triple. Nothing but the closure can read its rows, so every request loads all of a parent's rows and core's InMemoryLinkRows filters, sorts and pages them, on every provider; the container warm-up logs a notice for such a relation once it declares pivot fields, filters, sorts, an order, a count or a paginator. Its fillUsing() decides which rows exist, and the bundle then writes each member's meta.pivot onto the row the closure returns for it.

Members a closure queries with queriedBy()

When the members are computed, such as the values a setting may hold, and the application already filters and pages them in SQL, declare queriedBy(). Its closure receives the parent, core's LinkRowQuery and the request, and returns the page as a CollectionResult of IdentifiedMember values.

Scoping is the closure's job. The bundle doesn't narrow a queried relation by the scopes of its member types: no Doctrine query extension or scoping provider on a member type narrows its pages. A member the caller mustn't see still shows up if the closure returns it. The closure receives the request, so apply the caller's scope in its own query.

MorphToMany::make('options', ['publishers', 'countries', 'categories'])
    ->countable()
    ->queriedBy(static fn(Target $target, LinkRowQuery $query, JsonApiRequestInterface $request): CollectionResult
        => $options->page($target, $query, $security->getUser()))
    ->fields(Str::make('label')->readOnly())
    ->withFilters(Where::make('search'), Where::make('advertiser')->integer())
    ->withSorts(SortByField::make('label'))
    ->defaultSort(new SortDirective(SortByField::make('label'), descending: false))
    ->withoutRelatedEndpoint(),

GET /targets/{id}/relationships/options hands the closure the request's filters and sorts, every one the relation declares and none it doesn't, with the endpoint's page and whether ?withCount=_self_ counts it, and renders the page it returns, each member's row as its meta.pivot. Nothing loads all of a parent's members, and nothing narrows the query first, as the warning above says. The closure breaks ties so pages don't overlap. The related endpoint, when it is exposed, pages through the closure the same way and loads only that page's rows, one id IN (...) per type. ?withCount=options on a parent asks the closure for a counted empty page.

A parent's document renders the relationship's links and meta only, never data, and the closure doesn't run for it; ?include=options is a 400. Declare withoutRelatedEndpoint() when the member types are related-only, so only the relationship endpoint is routed.

Writes go through fillUsing(). A write that needs the current members reads every one through the closure, with no filters and no window: a replace that keeps the members a scope hides, a write of pivot fields, and the relationship write's response, whose linkage echo lists every member. Keep that cost in mind when a parent has many members.

The closure only ever receives an OffsetWindow or no window. A cursor paginator fails cache:warmup, whether it is the relation's own or the server's default the relation falls back to, with MorphToMany relation "options" declares queriedBy() and is paged by a cursor paginator, but its closure only ever receives an offset window. Give the relation an offset paginator with paginate(), such as PagePaginator or OffsetPaginator. The warm-up notice about in-memory link rows never fires for such a relation. Both the Doctrine and in-memory providers serve it alike, since neither queries it.

Flattened (on()) attributes and eager loading

A scalar attribute can be flattened from a chain of declared, to-one relations' related model with ->on('path') — the value reads from / writes onto the final related object in the chain, not the owning one. $path is a .-separated chain: 'author' (single hop) or 'publisher.country' (multi-hop). A backing relation may be hidden() (the idiomatic "internal association"), so the flattened attribute appears on the wire but the relation never renders as a relationship:

public function fields(): array
{
    return [
        Id::make(),
        Str::make('title')->sortable(),
        // `authorName` flattens the author's `name`: read renders author.name, write
        // mutates the loaded author's name. storedAs('name') maps the field's backing
        // member; on('author') names the to-one relation (honouring its column()/storedAs()).
        Str::make('authorName')->storedAs('name')->on('author'),
        // Multi-hop: `authorCountry` flattens author.country.name — the chain walks two
        // to-one hops. Any intermediate null short-circuits the read to null (and 422s a
        // write). Each hop is a declared to-one relation, validated at boot.
        Str::make('authorCountry')->storedAs('name')->on('author.country'),
        // A computed, read-only attribute (read-only on create AND update): the closure
        // supplies the value, which still gets the field's cast.
        Str::make('display')->computedUsing(
            static fn(mixed $model, JsonApiRequestInterface $request, string $name): string
                => 'Book: ' . $model->title,
        ),
        // The hidden backing relation: never a rendered relationship, but eager-loaded
        // for the flattened read/write (it backs `authorName` and the first hop of
        // `authorCountry`).
        BelongsTo::make('author', 'authors')->hidden(),
    ];
}

The trio is orthogonal: a plain attribute (Str::make('title')), a flattened one (->on('path')), and a computed one (->computedUsing($closure)) — on() and computedUsing() are mutually exclusive. The vocabulary is core's; see the core field-types page.

Read flattens model.seg1.…segN.member (any intermediate null yields a null attribute value, lenient). Write mutates the loaded final related model in place — Doctrine's unit of work auto-persists the dirty entity on flush, the in-memory store shares the reference, no related-persister change. A write where any hop is null is a 422 (RELATED_ATTRIBUTE_OWNER_MISSING, at /data/attributes/<name>) — a flattened attribute never auto-instantiates a missing related model.

Explicit change tracking. The write relies on Doctrine's default change-tracking policy (DEFERRED_IMPLICIT), under which flush() saves every managed entity that has changed. An entity mapped with DEFERRED_EXPLICIT (#[ORM\ChangeTrackingPolicy('DEFERRED_EXPLICIT')]) is only saved when it's passed to persist() itself, so a flattened write onto one is silently lost: the response shows the new value, but nothing reaches the database. The bundle only persists the resource being written. If a related entity uses explicit tracking, persist it yourself in a beforeUpdate hook, which runs before the commit's flush ($entityManager->persist($entity->author)), or keep the related entity on the default policy.

Eager loading. The bundle eager-loads every on() attribute's backing relation chain so the flattened read does not N+1 — one batched load per hop per page (a multi-hop chain loads in O(depth), a shared prefix loads once), the same batch as ?include (see doctrine.md → eager-loaded flattened attributes). The eager set (the dedup set of every on() chain) is never rendered as a relationship or in included unless also ?include'd, and bypasses the client-include safeguards (depth cap / allowed-paths / cannotBeIncluded) — it is author-declared and trusted, not client input.

Fail-loud, validated at boot. A malformed on() chain fails the build — at cache:clear / deploy, never as a runtime 500. Every segment must be a declared to-one relation: a to-many segment at any depth throws a LogicException at container warm-up (on() flattens a scalar from a to-one chain — a to-many is not flattenable; use ?include to materialise a collection), and the rule applies to every segment of a multi-hop chain, not just the leaf. A chain naming an unknown relation (a typo) also throws, so it never silently no-ops. A segment may be hidden() or visible — both are valid, because the chain is to-one.

Relations without a resource

Relations are a standalone capability: you can declare a type's relations with no AbstractResource. Put #[AsJsonApiRelations(type: …)] on a class implementing RelationsProviderInterface — its relations(): array returns the type's RelationInterface list:

#[AsJsonApiRelations(type: 'libraries')]
final class LibraryRelations implements RelationsProviderInterface
{
    public function relations(): array
    {
        return [
            BelongsTo::make('owner', 'users'),
            MorphToMany::make('items', ['tracks', 'albums', 'artists']),
        ];
    }
}

Autoconfiguration tags it haddowg.json_api.relations (RELATIONS_TAG); the bundle holds it in a lazy, type-keyed RelationsRegistry (type-keyed, not class-string-keyed, because relations are runtime objects core cannot read statically). The route loader gates the relationship routes on a type having relations — from a resource or a standalone provider — and TypeMetadataResolver sources relations resource-first then from the registry, so a resource-less type (paired with #[AsJsonApiSerializer]) gets identical relationship routes, rendering, and whole-resource relationship writes. See capability-composition.md for the wiring rationale.

The server argument on #[AsJsonApiRelations] assigns the type to the named server(s), the same as the resource attribute (→ multi-server-and-testing.md).

The example app declares all relations on resources, so the standalone form is shown here in prose; the bundle's RelationsRegistry/TypeMetadataResolver path is the same one resources take.

Next / see also

  • routing.md — the relationship/related route names and the segment-count ordering that keeps relationships from being captured as a {relationship} name.
  • data-layer.md — the mutateRelationship() and fetchRelatedCollection() SPI signatures and the whole-resource relationship-strip flow.
  • doctrine.md — the FK-vs-IN-subquery related-collection scoping and the load-state seam.
  • custom-data-providers.md — supplying a provider for a polymorphic to-many or any related collection the Doctrine reference cannot scope.
  • Core: relations, related-endpoints, relationship-mutation.