Skip to content

The Doctrine reference data layer

The bundle ships a reference data layer that turns any Doctrine-ORM-mapped entity into a fully queryable JSON:API type with no per-type code. Map an entity on a resource and the bundle's Doctrine DataProvider and DataPersister serve every read and write endpoint over it — translating ?filter/?sort/?page into DQL, scoping related collections, and committing hydrated entities through one EntityManager.

This page documents the Doctrine reference implementation: the entity-map compiler pass, the read and write pipelines, the DQL filter/sort translation, the related-collection scoping, instantiation, and the load-state seam. The storage-agnostic SPI these classes implement is on data-layer.md; overriding or scoping the Doctrine layer is on custom-data-providers.md.

The filter and sort vocabulary these handlers execute is core's — link filters and sorts for the value objects, pagination for OffsetWindow, and adapters for the FilterHandlerInterface/SortHandlerInterface these Doctrine handlers implement.

Activation: the entity map

The Doctrine layer is active only when both of these hold:

  1. doctrine/orm is installed (it is a suggest + require-dev dependency, not a hard one — see the optional-dependency matrix on configuration.md), and
  2. at least one resource maps an entity via #[AsJsonApiResource(entity: …)].

The layer supports doctrine/orm ^2.20 || ^3.2, with whichever DBAL and doctrine/persistence that ORM version installs. The bundle declares a conflict on anything outside that range, so Composer refuses an ORM 2.19, 3.0, 3.1 or 4.0 at install time rather than the first relationship query failing at runtime. ORM 3.0 and 3.1 declare the EntityManager's connection readonly, so once a failed flush has closed the manager, Symfony's kernel.reset can't give a worker's next request a fresh one. CI runs the full suite on ORM 3 and on ORM 2.20 with DBAL 3, doctrine/persistence 2.5 and Symfony 6.4.

You map an entity on the resource attribute:

#[AsJsonApiResource(entity: Album::class, server: ['default', 'admin'])]
final class AlbumResource extends AbstractResource
{
    public static string $type = 'albums';
    // …
}

— from AlbumResource, backed by the Album entity. The attribute and its arguments are covered on resources.md.

At container-build time DoctrineEntityMapPass collects every #[AsJsonApiResource(entity: …)] declaration and builds a type → entity-class map, keyed by the attribute's type override or the resource class's static $type (the same precedence the runtime registry uses). That map is injected into the Doctrine provider, the Doctrine persister, and (with no map argument) the load-state predicate.

When the map is empty — Doctrine is in the vendor tree but no resource maps an entity — the pass removes the Doctrine provider, persister, load-state and pivot resolver definitions entirely, so a non-Doctrine-integrated app never holds a definition referencing an absent EntityManagerInterface.

When the map is not empty, the container must have an EntityManagerInterface service, which doctrine/doctrine-bundle registers. Declaring entity: with doctrine/orm installed but no entity manager configured fails the build rather than leaving the Doctrine services pointing at a service that doesn't exist.

Build-time faults

These are all \LogicException at container build, never request-time errors:

Fault Message gist
entity: names a class that does not exist The entity class "…" mapped by #[AsJsonApiResource] on service "…" does not exist.
Type cannot be determined (no static $type, no type: override) Cannot determine the JSON:API type for the entity mapping on service "…".
Two resources map one type to different entities JSON:API type "…" is mapped to two different Doctrine entities: "…" and "…".
entity: is declared but there is no EntityManagerInterface service #[AsJsonApiResource(entity: ...)] maps type "…" (…) to a Doctrine entity, but the container has no Doctrine\ORM\EntityManagerInterface service. Install and configure doctrine/doctrine-bundle … or remove entity: …

Source: DoctrineEntityMapPass.

Two more checks run a little later — at cache warm-up (still cache:clear / deploy, so still the build, never a request) in the non-optional DoctrineServableWarmer, so a declaration that would only break at request time fails the build instead:

Fault Message gist
A sortable() / filterable column does not resolve to a real field/association (commonly a computed() field marked sortable, whose sort column defaults to the field name) The sort/filter "…" on JSON:API type "…" targets column "…", which is not a field or association on …
A pivot belongsToMany declaring a stored pivot field whose association entity cannot be discovered (one whose pivot fields are all computed needs none) Could not auto-detect a Doctrine association entity for the pivot relation "…" … Declare it explicitly with ->through(PivotEntity::class).
A pivot belongsToMany whose association entity holds several ManyToOnes that could be its parent side, or its related side, and whose relation doesn't name that side in through() (or, for the parent side, isn't stored as the parent's OneToMany mapped by it) The pivot relation "…" reads …, which holds several ManyToOne associations that could be its parent side, to …: owner, peer. Name the one that points back at the parent, such as ->through(Seat::class, parent: 'owner'). (or …its related side … such as ->through(Membership::class, related: 'user').)
A through(parent:, related:) name that is no ManyToOne of the entity to the parent's or the related type's entity The pivot relation "…" declares through(Seat::class, parent: 'rank'), but … has no ManyToOne "rank" to …. Its ManyToOne associations to … are: owner, peer.
A deprecated pivot.-prefixed WhereThrough, WhereThroughIn, WhereHas or WhereDoesntHave, or a pivot.-prefixed WhereHasMatching, whose path goes on from the pivot row to an entity no registered type serves, or several do The JSON:API resource for type "…" declares the filter "…" of relation "…", whose deprecated path "…" goes on from the pivot row to an entity no single registered type serves … Register exactly one resource type for that entity, or migrate the filter to a ->through() path that does not reach it.
A WhereMorph over a MorphTo identified only by a closure, or not at all, or over a MorphToMany without identifiedByRows() The filter "…" on JSON:API type "…" is a WhereMorph over the relation "…", which the Doctrine provider cannot query: declare the MorphTo with identifiedByColumns(type: ..., id: ...)…
A WhereMorph whose MorphTo names a column that is not a mapped field of the entity … whose identifiedByColumns() names "…", which is not a mapped field of …

The sort check validates the resolved column, so a computed() field marked sortable() that ALSO has a matching sorts() override supplying a real column passes. The pivot check runs the exact same discovery the first write would — only the timing moves. Source: DoctrineServableWarmer.

The map is keyed by type, so two (or more) resource types may map to the one entity — a full view and a curated view of the same record, for instance. The only mapping fault is the reverse: one type mapping to two different entities (the last row above). With two types over one entity, the Doctrine provider resolves each type to the same entity class and reads the same row by id — the type is supplied by the route (primary data) or the relation's declared make() type (linkage), never derived from the entity. See resources § One entity, two resource types for the worked users / public-profiles pair and choosing a relation's target view.

The read pipeline

DoctrineDataProvider answers fetchOne and fetchCollection over the EntityManager.

A collection fetch is one QueryBuilder pipeline:

  1. every supporting query extension customizes the builder first (base scopes the client cannot undo, eager-load joins);
  2. the shared CriteriaApplier (data-layer.md) matches the requested filter[…]/sort against the declared vocabularies and pushes each down through DoctrineFilterHandler/DoctrineSortHandler;
  3. for a windowed fetch, a COUNT runs over the filtered (un-ordered, un-windowed) query before the window applies as LIMIT/OFFSET — so items are never over-fetched and the reported total agrees with the applied scope.

A single fetch (fetchOne) runs the same extension pipeline — so a base scope holds for GET /{type}/{id} too — and falls back to EntityManager::find() (and its identity-map fast path) only when no extension supports the type. A row a scope excludes comes back as null, which the handler renders as a JSON:API 404.

The provider executes two windows, both pushed down to SQL. An OffsetWindow becomes LIMIT/OFFSET, and a CursorWindow becomes a keyset WHERE with its forced ORDER BY; see cursor pagination. Any other WindowInterface throws a \LogicException. The page-based paginators core ships all resolve to an OffsetWindow, and cursor pagination to a CursorWindow.

A collection action declared with filters reads its rows through the same provider (taking the type's filters). The builder runs the extensions as QueryPurpose::ActionCollection, then the action's filters, with no sort, window or count. FilteredCollection::query() hands that builder to the handler. each() reads it in batches keyed on the single id field, WHERE id > :last ORDER BY id LIMIT n. Before each batch after the first it detaches everything the loop loaded or persisted since the first batch, the same way a rollback does (see what a rollback leaves managed). What the EntityManager managed before the loop began stays managed and keeps its unflushed field changes, unless it points at a detached row or holds an unflushed collection change, when it is reloaded.

Source: DoctrineDataProvider.

Encoded resource ids (storage key != wire id)

A resource can decouple the JSON:API id a client sees (the wire id) from the storage key its entity is actually keyed by — exactly Laravel JSON:API's custom id encoding. Attach an encoder to the Id field with core's Id::encodeUsing(IdEncoderInterface):

public function fields(): array
{
    return [
        Id::make()
            ->encodeUsing(new ProductIdCodec())   // storage key <-> wire id
            ->matchAs('prod-[0-9a-f]+'),           // the route {id} requirement
        Str::make('name')->required(),
    ];
}
interface IdEncoderInterface
{
    public function encode(mixed $storageKey): string; // storage -> wire
    public function decode(string $wireId): mixed;      // wire -> storage; null when undecodable
}

The entity always holds the storage key. The transform runs at two boundaries:

  • Core owns the entity's-own-id transform: it encode()s the stored key on serialize (so the rendered id and every self/related link are wire ids) and decode()s a client-supplied id on create, setting the storage key on the new entity (a null decode is a 422). A server-generated id (no client id, the default) is the storage key's own wire form and is set as-is — it is never fed to decode(), so a server-minted create is not spuriously rejected. A PATCH does not set the id, so it needs no decode either. (A type whose id is database-generated has no id to hydrate on create at all; expose it without Create rather than mint a meaningless id — see the example's ProductResource.)
  • The reference Doctrine layer owns the id-as-lookup-key transforms, because the storage-agnostic DataProvider/DataPersister SPI passes ids as wire strings and keeps its signatures unchanged. Before the lookup the Doctrine provider decode()s the route {id}; a null decode short-circuits to a 404 (no row holds that key, so no query runs). Before getReference() the Doctrine persister decode()s each linkage id (keyed by the related type's encoder), so a relationship write whose data carries wire ids resolves the right managed references. The existence check before the write already refuses a linkage id that decode()s to null, or that no row holds, with a 404.

So a read round-trips wire -> (Doctrine decode) -> storageKey -> query -> entity -> (core encode) -> wire, and a create-with-client-id round-trips wire -> (core decode) -> entity (storageKey) -> persist -> (core encode) -> wire.

The uuid() / ulid() / numeric() / pattern() shortcuts set the route {id} requirement and the client-id format constraint; matchAs() sets the route requirement alone (the inner regex, no surrounding ^…$ — Symfony anchors it). The route loader stamps that requirement on every route carrying {id}, so a malformed id 404s at routing before any handler runs. A type with no encoder is unchanged (wire == storage), and the in-memory provider has no encoder at all, so encoding is a Doctrine-only concern — encoders are entirely user-supplied (no encoder dependency is added to the bundle).

Ids that are not an int or a string

The Doctrine layer reads each identifier's mapped type and converts ids through it. A Doctrine uuid id, for example, is a Uuid object on the entity, 16 bytes in the database on a platform without a native UUID type, and its RFC 4122 string on the wire. With such an id:

  • the provider binds the route {id} and every IN (...) list of ids in the database form, with the type's binding type, so an id stored as BINARY(16) matches. This covers fetchOne, include batching, related and relationship endpoints, withCount, the relatedQuery windows and the scoped id-IN probes;
  • the persister converts each linkage id to the form the entity holds before getReference(), so a relationship write sets a Uuid rather than a string. A linkage id the type cannot convert is a 404, as an undecodable one is;
  • rows are matched up by id in their database form, so an id read off an entity, one a query projected and one decoded from the wire all key the same row.

A uuid id needs no encoder: Id::make()->uuid() is enough, and the wire id is the canonical UUID string. An encoder still works: when its decode() returns the 16-byte form, the uuid type accepts that too.

Eager-loading includes (no N+1)

Eager-loading of a read's ?include tree is automatic and built in — there is no extra dependency to install (it used to require an external preloader library; that is gone, and the batching now lives in the bundle). Includes stop N+1ing with no per-type code. The bundle batch-loads the included relationships Laravel-style: one query per relation per level, no fetch-joins. Each level loads a relation for every source entity in a single WHERE id IN (…)-style query, and the loaded targets seed the next level.

Over the example, GET /albums?include=tracks across 16 albums issues 2 include-load queries (the albums, then one batched tracks load) — not the 1 + N a lazy render issues:

GET /albums?include=tracks&page[size]=100

The batcher reuses core's include decision, so it loads exactly what is rendered. This includes default includes: a resource's getDefaultIncludedRelationships() is applied by core as a fallback — when the request sends no ?include, the listed relationships are included (and now batch-loaded); an explicit ?include (even an empty ?include=) overrides the default.

final class AlbumResource extends AbstractResource
{
    // GET /albums with no ?include yields each album's artist in `included`
    // (rendered AND batch-loaded); ?include=… or ?include= overrides it.
    public function getDefaultIncludedRelationships(mixed $object): array
    {
        return ['artist'];
    }
}

— from AlbumResource.

The batch loads through the query extensions of the related type, so included and linkage hold exactly what the related endpoint returns (see relationships → included data is scoped like the related endpoint). A many-to-many or owning-side to-many include loads its rows by id in a second query, which runs the extensions again as QueryPurpose::IncludeHydration, so an extension can fetch-join what the included rows render (see shaping the include hydration query). When no extension applies to the related type, batching is a pure optimization and a relation it cannot batch falls back to a lazy load: a polymorphic relation, a composite-key target. With an extension, a polymorphic to-many or a composite-key target is refused with a 500 instead. An extractUsing() relation, or one stored on a non-association getter, always renders the model's own value. The relation's storage column drives the batch (column() ?? name()), so a storedAs() rename is honoured.

A paginated to-many renders its first page, read for the whole level in one bounded query per relation (see windowed includes). The rest of this section describes a relation that keeps its whole set: one declared withoutPagination(), or one exposing no endpoint.

Linkage that renders without an include goes through the same batch. A withData() to-many, or any to-many whose linkage data renders on a page of parents, loads in one query per relation per level, at the top level and below an include, instead of initialising each parent's collection on its own. A collection the unit of work has already initialised is read as it is, and relations stored on the same association share one load. A pivot belongsToMany loads through its pivot query run once for the whole page (see belongsToMany pivot data), and a to-one renders its identifier off the proxy without a load.

A batch keeps the order a lazy load of the collection would give. When the relation and its related type declare no defaultSort() and the request names no sort, it orders by the #[ORM\OrderBy] mapped on the association, included or not. A defaultSort() or a requested sort replaces that order.

The batching runs through the same provider-agnostic fetchRelatedCollectionBatch() seam that windowed related collections use, so it works on the in-memory provider too. A loaded to-many reaches the renderer out of band and never replaces the entity's collection, so a collection with no setter is fine. The witness is IncludePreloadTest.

Eager-loaded flattened (on()) attributes

The same batch also eager-loads the to-one chains a resource declares as load-not-render — so a flattened attribute (->on('path')) does not N+1. The eager set is the dedup set of every on() attribute's backing relation chain, declared by core's DeclaresEagerLoadsInterface::eagerLoadRelationshipPaths() (every AbstractResource satisfies it automatically) and executed by the bundle before the ?include walk.

Over GET /books flattening an authorName from a hidden author relation, the authors load in one WHERE id IN (…) query for the whole page — not one SELECT … WHERE id = ? per row (the per-row N+1 the flattened read would otherwise introduce, since the author association is lazy). An on() chain may be multi-hop (->on('author.country')): the bundle walks it hop by hop, so the second hop loads in one WHERE id IN (…) too — O(depth), no per-row SELECT at any hop. It is the same batch as ?include, with these eager-only properties:

  • Never rendered. An eager relation is loaded onto the parent's column exactly as a lazy read would have materialised it, but rendering stays gated on core's isIncludedRelationship, which the eager set never touches. So a hidden on() backing relation (at any nesting depth) is loaded but never appears as a relationship or in included unless also ?include'd — eager-loading changes only the query plan, never the document.
  • Fail-loud at boot. An on() chain is validated at container warm-up (cache:clear / deploy), so a bad declaration fails the build — never a runtime 500. Every segment must be a declared to-one relation: a to-many segment at any depth throws a LogicException (on() flattens a scalar from a to-one chain — a to-many is not flattenable; use ?include), and the rule bites every segment of a multi-hop chain, not just the leaf. An unknown segment (a typo) also throws (no silent no-op). A segment may be hidden() or visible — both are valid, because the chain is to-one.
  • Bypasses the client-include safeguards. The eager set is author-declared and trusted, so the include depth cap / allowed-paths whitelist / cannotBeIncluded (which gate untrusted client input) do not apply to it.
  • Resolved hidden-inclusive. An on() attribute's backing relation is idiomatically hidden() (the internal association), so the eager loader resolves it against the hidden-inclusive declared-relation set — a hidden relation is found and loaded even though it never renders.

A flattened-attribute write (PATCH setting authorName, or a multi-hop authorCountry) mutates the loaded final related model in place; Doctrine's unit of work auto-persists the dirty loaded entity on flush (no related-persister change). A write over a null hop is a 422 (RELATED_ATTRIBUTE_OWNER_MISSING) — a flattened attribute never auto-instantiates a missing related model.

Windowed includes (window_functions)

A to-many whose linkage renders, included or declared withData(), renders its first page. The provider reads every parent's first page as ONE bounded native ROW_NUMBER() OVER (PARTITION BY parent ORDER BY …) query per relation, fetching only ~one page per parent plus, when the page is counted, the real per-parent total (COUNT(*) OVER), never the parent's whole set. The related type's query extensions narrow the inner query, so a soft-deleted or other-tenant row never takes a place on the page. A relation with no default order is cut in its association's mapped #[ORM\OrderBy], the order a lazy load gives it, and the related endpoint serves the same order. A relation declared withoutPagination() keeps the whole-set fast path above.

[!IMPORTANT] json_api.doctrine.window_functions defaults to true and needs SQL window functions: MySQL ≥ 8, MariaDB ≥ 10.2, SQLite ≥ 3.25, or any PostgreSQL. On an older engine the first windowed include throws a 500 (logged, naming these floors). Set it false to use the per-parent bounded fallback — one real LIMIT/OFFSET query per parent (no window function), rendering byte-identical documents:

# config/packages/json_api.yaml
json_api:
    doctrine:
        window_functions: false

There is no auto-detection (no probe/cache/fallback-on-error); the switch is explicit.

Two native shapes mirror the related-collection scoping: an inverse-FK OneToMany partitions by the related table's parent FK and hydrates the entity inline (one statement); an owning-side / many-to-many relation joins the join table, partitions by its parent column, and id-loads the distinct related entities (two statements — the ORM object hydrator would otherwise dedup a member shared across parents). The ORDER BY appends a PK tiebreak (matched in the in-memory witness) so ties resolve identically on both providers.

A filtered windowed include (relatedQuery[<rel>][filter][…]) runs as ONE bounded native query too: the inner scoped query carries the relatedQuery filter through the same DQL filter executor the related-collection endpoint runs, then is wrapped with the window functions — so a filtered windowed include is also one bounded query on on, with the filtered per-parent total. Only window_functions: false takes the per-parent bounded fallback. The join-table shape's id load runs the related type's extensions under IncludeHydration, as the whole-set pair query's does. A pivot belongsToMany windows its grouped pivot query the same way, in one statement that carries each member's pivot values (see belongsToMany pivot data). See pagination → windowed includes.

The write pipeline

DoctrineDataPersister is the write twin of the provider, committing through the same EntityManager the provider reads with.

  • create() is persist() + flush(). It makes no assumption that the id is pre-set: with the store-provided default (a #[ORM\GeneratedValue] column), the bundle's hydrator sets nothing on the id and Doctrine assigns it on flush — the handler then reads it back (via the serializer's id accessor) for the 201 body and Location. So a plain Id::make() over an auto-increment entity round-trips the database-assigned id with no persister change (see resources § Sourcing the resource id). An id already on the new entity is a client id, and when a row with it exists the create is a 409 CLIENT_GENERATED_ID_ALREADY_EXISTS rather than the database's unique-key error. The lookup goes through find(), so a Doctrine filter can hide the row from it, and a concurrent create can insert the id after it. Either way the insert then breaks the primary key, and the persister answers the same 409 when that violation came from its own row's insert and a row with the id is there. If the database refuses that second lookup, as PostgreSQL does in a failed transaction, the violation stays a 500. The create runs inside the write's transaction, so the persister sets a savepoint before inserting a client id and rolls back to it before the lookup, which keeps PostgreSQL answering it on DBAL 3 with savepoints off as well as on DBAL 4. An entity the EntityManager already manages, because a before hook persisted or flushed it, is not looked up: the row it holds is its own, and an insert still to come is checked by the violation as above. The in-memory persister refuses a taken id the same way, and likewise accepts the entity a hook already saved.
  • update() relies on the target being a managed instance the hydrator mutated in place — the provider loaded it through this same EntityManager, so update() is just flush(). There is no persist/merge.
  • delete() is remove() + flush().
  • Every write runs in a transaction. The handler opens one through the persister before the write's first step (see lifecycle hooks), so each flush above, and any flush a before hook makes, is undone if a later step throws. commit() commits and flushes nothing itself. rollback() rolls the connection back to where the transaction began, closing any transaction a hook opened inside it, and detaches what the write touched while keeping managed what the EntityManager held before (see what a rollback leaves managed). The manager stays open for the error response and the rest of the request. The persister is reset between requests (kernel.reset), so a worker never starts a request inside a transaction an earlier one left open.
  • Client date-times are written in the storage zone. A client may send 2026-10-01T16:00:00Z to a naive datetime column. Before core hydrates a create or update, each DateTime attribute the request sends for such a column is moved to the same instant in PHP's default timezone, and so is each DateTime pivot field written from meta.pivot. Without that, the column would store 16:00:00 as local time, and under America/New_York it would read back four hours late. Only values the request wrote are converted. A date-time your own code sets on the entity, in a hook or a setter, is persisted exactly as given. Reads render through the usual output_timezone. Only a field documented as an RFC 3339 date-time is converted, since the moved value is written back in that shape. A field with a custom format() is hydrated as sent, so if that format carries an offset, such as D, d M Y H:i:s O, its column stores the wall clock of the offset the client wrote.
  • Numbers are written to a decimal column as decimal strings. Doctrine reads a decimal column as a string, so its property is usually typed string, while a Decimal field hydrates a float. A number written to a decimal column, as an attribute, a flattened on() attribute or a pivot field, reaches the entity as a plain decimal string rounded and padded to the column's scale: at scale 2, 19.99 is stored as "19.99", 19.9 as "19.90", 20 as "20.00" and 19.999 as "20.00". On a database with a decimal type the string matches what Doctrine reads back, so writing the stored value again leaves the entity unchanged. SQLite has no decimal type and reads the value back unpadded, "19.9" rather than "19.90" and "20" rather than "20.00", so a value read back can differ there from the string that was written. The member is the setter when the entity has one, as core writes it, and the property otherwise. A member typed to refuse a string, such as float, still gets the float. The value can't carry more digits than a PHP float holds, since the request body is decoded as JSON first: 1.10000000000000001 arrives as 1.1. A persister that decorates the Doctrine persister keeps the conversion for attributes, which go through core's storage cast. A pivot value written to a declared link row asks the persister instead, so a decorator that should store it as a decimal string implements haddowg\JsonApiBundle\DataPersister\StoresDecimalsInterface and delegates decimalForColumn() to the Doctrine persister. Without it, that value is written as the pivot field cast it, a float that a property typed string refuses. A decorator of the Doctrine persister also implements Symfony\Contracts\Service\ResetInterface and delegates reset(), because Symfony moves the Doctrine persister's kernel.reset tag onto the decorator.

The managed-update coupling is the one constraint a custom data layer must respect: a provider that returns a detached entity from fetchOne would silently break Doctrine updates, because there would be nothing managed to flush. Provider and persister must share the EntityManager — the reference pair does. If you replace one of them for a type, replace both (see custom-data-providers.md).

Source: DoctrineDataPersister.

What a rollback leaves managed

A write that fails rolls the database back, but Doctrine's unit of work still holds what the write did in memory. If that stayed, a later flush in the same request, or in the same test, would write the rejected changes after all. Detaching everything instead, as a plain EntityManager::clear() does, also detaches entities the request still uses, such as the security user. A listener like Gedmo's Blameable then hands the detached user to the next flush, which sees it as new and inserts it again.

So when beginTransaction() opens a transaction, the persister notes every entity the EntityManager manages at that moment, and what each holds. After rollback() has rolled the connection back:

  • Every entity managed before the transaction began stays managed with the same object identity, so code holding it carries on.
  • One of those the write changed is reloaded from the database: a field or association the write set, flushed or not, a collection it changed or loaded, or a reference to an entity being detached. Its unflushed changes are dropped, including ones you made before the write and didn't flush.
  • Everything else is detached: whatever the write loaded, persisted or inserted, and every entity it deleted or scheduled for deletion. An entity you persisted before the write and hadn't flushed yet is detached too. Flush your own changes before a write starts if they must survive its failure.

Nested transactions each keep their own list, so rolling back an inner one keeps what the outer one had loaded. An Atomic Operations batch rolls back through the same path.

The persister doesn't detach entities one at a time. Detaching cascades along cascade: ['detach'] and cascade: ['all'] mappings, so detaching a rolled-back row could detach the security user it points at. A detach also leaves behind the orphan removals and collection deletions the write scheduled, which the next flush would still run. Instead it clears the unit of work, registers the kept entities again with the identity and original data they had, and reloads the changed ones through their entity persister, which doesn't cascade either. Clearing dispatches Doctrine's onClear event, as the full clear before it did.

When the write fails in a flush, Doctrine closes the EntityManager before the rollback runs, and a closed manager can't be put back. Every entity loaded from it is unusable for writing, the security user included, until kernel.reset replaces the manager for the next request. Don't hold managed entities across a write whose flush failed; in a test, reload them from the new manager.

Relationship write query cost

Before a write applies any linkage, the handler checks that each id names a row, with one batched SELECT … WHERE id IN (…) per related type through the provider's fetchByIds() (see written linkage). The rows it loads stay in the identity map. The persister then resolves each linkage id with EntityManager::getReference(), which returns the managed entity already loaded, so resolving costs no further query:

  • A many-to-many the parent owns (the join-table side, e.g. editors) adds each entity to the owning collection and the join row inserts from its id. Creating or replacing such a relation with 2 ids or 200 issues the same number of SELECTs: the one existence check.
  • An inverse one-to-many (the foreign key lives on the child, e.g. comments where comment.article_id is the FK) sets each child's owning-side association ($comment->article = $article). The child is already managed, so that loads nothing more either. Re-pointing N children still writes N rows at flush: the unit of work tracks each FK change, and the only alternative, a bulk UPDATE … WHERE id IN (...), would bypass the unit of work and the children's lifecycle and cascade events. If you need that, supply a custom DataPersister that issues the bulk update.

DoctrineWriteQueryBudgetTest pins both costs, and DoctrinePivotWriteQueryBudgetTest pins a pivot write to the same single read: the pivot's pre-validation and the existence check share it.

Owned aggregates: orphan removal on detach

Replacing or removing a to-many relationship (PATCH/DELETE …/relationships/{rel}, or a relationships member in a whole-resource write) mutates the managed owning collection in place — clear() then rebuild on a replace, removeElement() on a remove. So Doctrine's own orphanRemoval: true is honoured for free: a child dropped from a collection whose association declares it is deleted at flush, not merely detached (its FK nulled). Model a composition — an Album owns its Tracks — with orphanRemoval: true on the inverse OneToMany, and a relationship replace that omits a track deletes the orphaned row. Nothing in the bundle toggles this; it follows entirely from the entity mapping (a plain detach when the association does not declare orphanRemoval). The persister never bypasses the collection (it issues no bulk FK UPDATE), which is exactly the precondition the unit of work needs to schedule the orphan delete. This is the Doctrine-native equivalent of Laravel's deleteDetached — declared on the mapping, not a resource flag.

Moving a child between parents

On an inverse one-to-many each child points at exactly one parent, so adding a child to articles/1 that currently belongs to articles/2 takes it out of articles/2. Before an add or replace, the persister reports each child whose parent would change (ReportsMovedMembersInterface), and the handler dispatches a BeforeMemberMoveEvent for it. The bundle's security subscriber allows the move when the caller passes the relation's mutate gate (or the type's securityUpdate) for the parent the child leaves, or the child type's securityUpdate for the child itself. A child with no parent needs the latter. Anything else is a 403, and nothing is written. A type with no security declared moves children as before.

A remove only detaches current members. Naming a child that belongs to another parent leaves it where it is, as the JSON:API spec requires of removing a non-member.

A child whose foreign key to the parent is NOT NULL (#[ORM\JoinColumn(nullable: false)]) can't be left without a parent. A remove that names it, or a replace (at the relationship endpoint or in a whole-resource write) that leaves it out, is a 403 (REMOVAL_PROHIBITED, or FULL_REPLACEMENT_PROHIBITED for the replace), and nothing is written. When the inverse side declares orphanRemoval: true the child is deleted instead, so the write goes ahead.

Instantiation

On create, the persister builds the entity through its constructor when the constructor needs no argument. So an id the constructor mints, such as a UUIDv7, and the collections it initialises are there before the body is hydrated:

#[ORM\Entity]
class PlaceholderDefinition
{
    #[ORM\Id]
    #[ORM\Column(type: 'uuid')]
    public Uuid $id;

    #[ORM\OneToMany(targetEntity: TemplatePlaceholder::class, mappedBy: 'definition')]
    public Collection $usages;

    public function __construct()
    {
        $this->id = Uuid::v7();
        $this->usages = new ArrayCollection();
    }
}

An entity whose constructor needs arguments is built with ClassMetadata::newInstance() instead, the mechanism the ORM uses to hydrate an entity on read, so it still works under the generic engine without a custom persister. Its constructor does not run, so an id or a collection it would set is missing. The persister does re-initialise an uninitialised to-many collection before applying embedded relationships, so a create that sets a to-many does not hit an "accessed before initialization" \Error.

The same rule builds a new pivot or link row. A constructor-minted id counts as a client id when the persister checks for a taken one, so a create of such an entity looks its id up once before the insert.

To build an entity whose constructor needs arguments, or through a factory, implement InstantiatesEntityInterface on the resource. Its instantiate() builds the model every create of the type hydrates, an Atomic Operations add included, and the persister's own instantiate() is skipped:

use haddowg\JsonApiBundle\Hook\HookContext;
use haddowg\JsonApiBundle\Hook\InstantiatesEntityInterface;

final class AdvertiserResource extends AbstractResource implements InstantiatesEntityInterface
{
    public function __construct(private readonly string $defaultCurrency) {}

    public function instantiate(HookContext $context): object
    {
        return new Advertiser($this->defaultCurrency); // a constructor argument the persister can't supply
    }
}

A type with no resource implements it on its standalone hydrator instead.

Pivot rows

A row the persister adds to a pivot belongsToMany's association entity is built through its constructor when the constructor needs no argument, so an id or a collection the constructor sets is there when the row is persisted. A constructor that needs arguments is skipped, as for an entity. To build those rows, implement InstantiatesPivotInterface on the resource that declares the relation, or on the type's standalone hydrator when it has none. It runs for every new row, whatever write adds it, and returns null to leave a relation to the persister:

use haddowg\JsonApiBundle\Hook\HookContext;
use haddowg\JsonApiBundle\Hook\InstantiatesPivotInterface;

final class TemplateResource extends AbstractResource implements InstantiatesPivotInterface
{
    public function instantiatePivot(HookContext $context, object $parent, object $related, array $pivot): ?object
    {
        return $context->relation?->name() === 'pinned'
            ? new PinnedPlaceholder($parent, $related)
            : null;
    }
}

The persister sets the row's two associations and writes its pivot fields after the hook returns. $pivot is the member's meta.pivot as sent.

Deleting without the persister

A type that deletes differently, such as a soft delete through a domain service, implements DeletesEntityInterface on its resource. The handler then calls its delete() in place of the persister's, after the before-delete gates and before the after-delete hooks. Every other write still goes through the Doctrine persister, so there is no persister to write or decorate. The hook makes its own change, inside the delete's transaction: its flush commits once it returns, and a throw from it rolls back what the before-delete hooks wrote too:

use haddowg\JsonApiBundle\Hook\DeletesEntityInterface;
use haddowg\JsonApiBundle\Hook\HookContext;

final class AdvertiserResource extends AbstractResource implements DeletesEntityInterface
{
    public function __construct(private readonly AdvertiserManager $advertisers) {}

    public function delete(object $entity, HookContext $context): void
    {
        $this->advertisers->archive($entity); // sets the flag and flushes
    }
}

A soft-deleted row is still found by the provider unless a query extension hides it.

Filter translation to DQL

DoctrineFilterHandler executes core's filter value objects against the QueryBuilder, pushing each predicate down as a parameter-bound andWhere. The semantics mirror core's in-memory ArrayFilterHandler (the conformance witness), so the same spec test passes on both providers.

Core filter VO DQL translation
Where (=/==/===) = :param (DQL has one type-coercing equality)
Where (!=/<>) <> :param
Where (>/>=/</<=) the same operator, :param-bound
Where (like) LOWER(col) LIKE :param ESCAPE '!' (%v%) — contains-match, ASCII case-insensitive
Where (starts/ends) LOWER(col) LIKE :param ESCAPE '!' with v% / %v — prefix / suffix (StartsWith / EndsWith)
Range / DateRange two push-down >= :min / <= :max predicates over the present bounds, on the same query
WhereIn / WhereIdIn col IN (:list)
WhereNotIn / WhereIdNotIn col NOT IN (:list)
WhereNull / WhereNotNull col IS NULL / col IS NOT NULL (request value ignored)
WhereSet col IS NOT NULL for true, col IS NULL for false, no predicate for both
WhereMorph over a MorphTo typeCol IN (:types) and, when ids are sent, idCol IN (:ids) on the columns identifiedByColumns() names, each id bound as its storage key and its wire id; idCol is also kept to the ids the requested type's query extensions admit, when it has any
WhereMorph over a MorphToMany a correlated EXISTS over the through() entity identifiedByRows() names, its owner the outer row, its type and id compared and scoped as for a MorphTo
WhereHas / WhereDoesntHave correlated EXISTS / NOT EXISTS subquery
any of the above with ->through() one correlated EXISTS joining each relation of the path, each reached entity kept to the rows its type's query extensions admit, with the filter's own translation applied to the last one
WhereThrough (deprecated) dotted-traversal correlated EXISTS (the related entity narrowed by the leaf comparison)
WhereThroughIn (deprecated) the same correlated EXISTS with IN (:list) at the leaf; an empty list is 1 = 0
WhereHasMatching correlated EXISTS whose related entity is narrowed by an author-supplied Criteria/closure (Doctrine-only)
WhereAll / WhereAny the children recombined with andX() / orX() as one composite andWhere (see below)
Where pinned with ->fixed() the same DQL as the underlying Where, its compared value pinned server-side (no dedicated arm — it rides the deserialize seam)
a custom FilterInterface a registered DoctrineFilterArmInterface that supports it; else core UnsupportedFilter

A few translations carry nuance:

  • like is contains, ASCII-case-insensitive. The value's %/_ are escaped as literals (with !), wrapped in %…%, and both sides are LOWER()ed so the result does not depend on the platform's LIKE collation (PostgreSQL's LIKE is case-sensitive; SQLite folds ASCII only). Case-folding beyond ASCII remains platform-defined. A non-string filter value matches nothing (stripos requires two strings).
  • A uuid value matches in either case. An equality filter whose value is a uuid in its canonical 8-4-4-4-12 hex form, which is Where with =, ==, ===, != or <>, WhereIn, WhereNotIn and the id filters, binds the value as sent and its lower- and upper-case forms: col IN (:forms), or col NOT IN (:forms) for a negated one. The column itself is never wrapped in LOWER(), so an index on it still serves the query, and a uuid whose letters mix cases in the column matches only as sent. The same holds at the field leaf of a ->through() path, WhereThrough and WhereThroughIn, on a pivot row and in a relatedQuery filter. A column whose type reads every form as one value, such as a Symfony uuid column or a guid PostgreSQL keeps as a native uuid, keeps its single = :param. The ordered operators, Range, DateRange, like, starts and ends are unchanged, and every value that is no uuid compares exactly.
  • starts/ends mirror like's fold. The two prefix/suffix operators (backing the StartsWith/EndsWith convenience filters) reuse the same wildcard-LIKE helper — same %/_ escaping, same LOWER() both sides, same non-string → no-match — differing only in where the % wildcard wraps (v% for starts, %v for ends), so they match the in-memory stripos === 0 / str_ends_with exactly.
  • Range/DateRange are two push-down predicates, not a subquery. A structured Range adds a >= :min and/or <= :max over the present bounds onto the same primary query — one query, no join, no subquery, no N+1. A blank/absent bound is open-ended (treated as absent, byte-for-byte with the in-memory bound()), so an open filter[<key>][max]= is a no-op rather than a 400; DateRange binds each bound as a coerced \DateTimeImmutable, converted for the column as described in Date-times in naive columns.
  • Lists. A set filter declared with acceptsList() reads its value through core's ListValue::members(), as the in-memory handler does: an array as is, a string split on the delimiter while the list is delimited and kept whole when it is array-only. Without acceptsList() an array passes through and a string is split. A WhereIn or WhereNotIn declaring deserializeUsing() then hands the members to that closure in one call and binds the list it returns, as the in-memory handler does.
  • Empty-list semantics. WhereIn/WhereIdIn with an empty list match nothing (IN () is not valid SQL, so the handler emits 1 = 0); the negated variants then match everything (a no-op). An empty list a deserializeUsing() returns is treated the same way.
  • WhereMorph compares declared fields. A MorphTo it filters must declare identifiedByColumns() and a MorphToMany must declare identifiedByRows(), since a closure from identifiedBy() can't be compared in a query. The stored type values come from the declared typeMap, or are the JSON:API type itself, and each id is decoded through its type's encoder and bound in both forms, the storage key and the wire id, since the column may hold either. A filter over a relation declaring neither fails cache:warmup.
  • A scoped WhereMorph admits ids as a related read does. When the requested type has query extensions, requested ids are admitted with one id query through the type's encoder and its id's Doctrine type, as GET /{type}/{id}/{relation} loads them, and only the admitted ids are bound. With no ids sent, a type that declares no encoder keeps one subquery, idCol IN (<the admitted ids>), when idCol and its id column are of one family, both integers (integer, bigint, smallint) or both text (string, ascii_string, text). A Symfony uuid id, and a guid PostgreSQL keeps as a native uuid, also keep the subquery against a text idCol, with the id read as its canonical lowercase text inside it: BIN_TO_UUID() on MySQL 8, a cast on PostgreSQL's native uuid, and a LOWER(HEX()) expression with dashes on MariaDB, older MySQL and SQLite. Only the canonical lowercase text matches that way, which is what a uuid with no encoder stores. Any other type, such as an encoded id, a ulid, an integer id under a text column, which PostgreSQL has no comparison for, or a platform with none of those expressions, first reads the distinct ids of that type the column holds, admits them the same way and binds the result in lists of 2000 joined with OR, so a long list stays under the database's parameter limit. That costs one extra query, bounded by the targets the rows name rather than by the target table.
  • WhereAll/WhereAny recombine their children with andX()/orX(). A server-composed group is applied by running each child through the same dispatch a top-level filter uses — fanning the group's request value uniformly to every child — capturing the predicate it pushes down, then recombining the captured predicates with andX() (WhereAll) or orX() (WhereAny) as one composite andWhere. So a fanning group is a multi-column search (filter[q]=foo → LOWER(name) LIKE '%foo%' OR LOWER(email) LIKE '%foo%') and a fixed-child group a canned toggle. Each child binds its own parameters on the query with the usual count-derived, collision-free placeholder names — so repeated columns and arbitrarily nested groups (A AND (B OR C)) bind distinctly. A ->fixed() Where needs no arm of its own: its pinned value rides the existing deserialize seam, so the Where translation above runs it unchanged (col = :param with the server-set literal bound).
  • WhereHas/WhereThrough/WhereHasMatching share one EXISTS builder. All three relationship filters push down through one correlated EXISTS (NOT EXISTS for WhereDoesntHave) subquery rooted on the related entity (the first hop's target) and correlated back to the outer owner by a membership IN-subquery on the owning association (uniform for to-one and to-many, owning-side and many-to-many). This is set-membership, not a join into the primary SELECT, so primary rows are neither duplicated nor in need of DISTINCT, it never hydrates the relation (linkage / ?include / the relationQuery profile compose for free), and a to-one and a to-many translate identically. The three front-ends differ only in what they ask of that builder: WhereHas/WhereDoesntHave are the degenerate pure-existence path (no leaf predicate); WhereThrough chains the path's intermediate segments as joins off the related root and compares the final segment as the leaf, and WhereThroughIn does the same with an IN over the list; WhereHasMatching narrows the related root with an author-supplied predicate. See the relationship-existence filtering subsection below.

The example AlbumResource declares two of them:

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

public function filters(): array
{
    return [
        // filter[tracks]=1 — albums with at least one related track.
        WhereHas::make('tracks'),
        // filter[artist.name]=Radiohead — EXISTS-ANY over the album's artist.
        WhereThrough::make('artist.name'),
    ];
}

— from AlbumResource. GET /albums?filter[tracks]=1 keeps albums with at least one related track, and it ANDs on top of the published base scope — an app-supplied query extension, the example's PublishedAlbumsExtension; the DoctrineExtensionTest asserts exactly that composition.

A filter family never reaches the handler. ?filter[value.cap]=5 is matched by core's FilterMatcher, the family resolves cap with the request, and the handler sees the filter it returned: a Where or WhereIn translates as above, anything else goes to its arm like any custom filter. The same matching runs for the primary collection, related and relationship endpoints, relatedQuery[<path>][filter], ?withCount counts and a collection action's filters. The cache warmer cannot check a family's columns, since it resolves them only against a request. A traversal filter a family returns has its path resolved then too. On a relation read through its pivot rows, a pivot.-prefixed path that reaches an entity no single registered type serves, which the warmer refuses on a declared filter, answers 500 and logs the family and the path.

Source: DoctrineFilterHandler.

Date-times in naive columns

Doctrine's datetime and datetime_immutable types write Y-m-d H:i:s and drop the offset, and read the column back in PHP's default timezone. So the column holds local time in that zone. A client bound such as filter[startsAt][min]=2026-10-01T15:00:00Z is an instant, and binding its 15:00:00 against local times would compare the wrong moment. Under America/New_York a row stored as 2026-10-01 12:00:00, which is 16:00Z, would be left out.

The handler therefore looks up the compared column's mapped type and binds a \DateTimeInterface value with that type. For a naive datetime type or a subclass of one, it first converts the value to PHP's default timezone. That covers DateRange, Where and its comparison presets when their deserializer yields a date, and a WhereThrough leaf. The timezone is read with date_default_timezone_get() on every bind, so an application that switches it per request, say per tenant, gets the right zone each time. Writes are converted the same way.

Binding with the mapped type matters on its own. Without it Doctrine infers the type from the value, so a bound against a datetimetz column would be formatted without its offset. With it, a datetimetz bound keeps its offset and is not converted.

A date column is not converted either, because moving a midnight bound into another zone can change its day. A DateRange over a column a Date field backs takes a full date for each bound, filter[day][min]=2026-10-01, documented as format: date. It binds with the column's own date type, so it compares as the calendar day the client wrote, as the in-memory provider does.

Cursor pagination keys are not converted. A cursor carries the row's value as the provider read it, so its wall-clock time already matches the stored column.

Filters reaching through relations: ->through()

A filter declared with ->through() reads a field of the type its path of relations reaches. The handler joins every relation of the path inside one correlated EXISTS, so a to-many hop neither multiplies rows nor loads the relation, and applies the filter's own translation from the table above to the entity the last join reaches. For campaign.advertiser and a Where on the advertiser's name, with the membership correlation elided:

WHERE EXISTS SELECT 1 FROM campaign c INNER JOIN advertiser a ON a.id = c.advertiser_id
  WHERE c.id IN correlated-membership AND a.id IN scoped-advertiser-ids AND a.name = ?

Each entity a hop reaches is kept to the rows its type's query extensions admit, applied under QueryPurpose::FetchRelatedCollection to a subquery of that entity's ids, so a row a scope hides matches no filter. A relation that holds nothing gives the EXISTS no row, so it never matches, WhereNull and WhereSet sent false included; an existence filter at the end of a path, such as WhereDoesntHave::make('unadvertised', 'advertiser')->through('campaign'), is how to find empty relations, and it counts only the rows the scope admits. A wire id the leaf compares is decoded once, by core, through the reached type's encoder.

The warm-up refuses a path the provider can't run, naming the filter: a segment that is not an association of the entity it starts from (a pivot belongsToMany is joined through its association entity), a hop into a type no entity maps or one a provider other than Doctrine scopes, and a leaf that is not a field or association of the reached entity.

Paths through a pivot row

A pivot segment in the path reaches the pivot rows of a belongsToMany with stored pivot fields, over the association entity behind it. A path that starts with pivot reads the pivot row of the relation it runs under, which the relation's pivot query has joined as pivot, so it applies wherever the pivot. column filters do: the related and relationship endpoints and relatedQuery[<relation>][filter]. Ending there, the filter applies to that row's pivot field. Elsewhere it is unrecognised, as a pivot. column filter is.

A pivot in the middle of a path joins the association entity's rows linking the row before it to each member, inside the same EXISTS, with the member joined too and kept to the rows its type's query extensions admit, so a link to a hidden member never matches.

After pivot, a segment names an association of the association entity, such as pivot.addedBy. The provider reads the type it reaches from the entity it targets: the one registered type whose entity that is. The warm-up refuses an association whose target no registered type serves, or several do, and a pivot after a relation the provider reads no pivot rows of, which includes a morphToMany: its link rows aren't walked by a path yet. From the type it reaches, the path is scoped and gated like any other hop. A pivot hop itself is gated by its relation's read permission.

A sort takes only a leading pivot, and orders the relation's members by a pivot field or by a field of a to-one association of the pivot row, left-joined from pivot. The in-memory provider holds no pivot rows, so it refuses every filter whose path reaches one with a 400.

Relationship-existence filtering: WhereHas, WhereThrough, WhereHasMatching

WhereThrough and WhereThroughIn are deprecated in favour of ->through() and are removed in the next major version; they keep the behaviour described here until then.

Three filters keep a row by what its relationships contain, never by a column on the row itself. All three execute as the single correlated EXISTS subquery described above, so they share its properties: no fetch-join, no row multiplication, and free composition with linkage / ?include / the relationQuery profile.

The subquery correlates to the entity the filter runs on. On a related collection that is the query root; on a ?withCount total or a windowed ?include, where the query joins the related entity to its parent, it is that joined entity. So relatedQuery[leads][filter][brand.name]=Acme with ?withCount=leads counts each campaign's leads whose brand is Acme, the same total the related endpoint reports.

  • WhereHas / WhereDoesntHave — pure existence. They ignore the request value and match rows whose named association has (WhereHas) or lacks (WhereDoesntHave) at least one related row.

  • WhereThrough — dotted-path traversal, the constrained-existence filter. WhereThrough::make('artist.name') responds to filter[artist.name] and keeps a row whose artist's name matches — an EXISTS-ANY semi-join. Every intermediate segment is a relationship (to-one or to-many, both translate identically as "there exists a … whose …") and the final segment is the compared attribute, so the path chains: filter[author.company.name]. The wire key carries the dots by default; supply an explicit key with the two-argument form (WhereThrough::make('topArtist', 'artist.name') → filter[topArtist]). The leaf comparison shares Where's operator vocabulary (=, !=, >, like, …) via the fluent operator() setter (default =), and it is value-validated (the numeric()/integer()/pattern()/constrain() shortcuts, see data-layer → validating filter values) and portable: core ships the metadata + an in-memory traversal, so the same filter[artist.name] runs on both providers (the in-memory provider walks the object graph; the Doctrine reference renders the correlated EXISTS rooted on the related Artist). The example's AlbumResource declares it — GET /albums?filter[artist.name]=Radiohead keeps Radiohead's albums.

  • WhereThroughIn — WhereThrough with an IN at the leaf. However many values the list holds, the query carries one subquery:

WHERE EXISTS (
  SELECT 1 FROM campaign c
  INNER JOIN advertiser a ON a.id = c.advertiser_id
  WHERE c.id IN (SELECT ... correlated to the outer lead ...)
    AND a.id IN (?, ?, ?)
)

An empty list adds 1 = 0 and no subquery.

  • Paths that end on a relationship. When a WhereThrough or WhereThroughIn path ends on a relation (campaign.advertiser, or a bare templates), every segment is joined and the leaf compares the identifier of the entity the last hop reached, through the same id path the rest of the provider uses, so an id that is itself an association compares as IDENTITY(alias.field). The values are the decoded storage keys, bound with the id's Doctrine type, so a binary uuid id matches. See relationships for how paths resolve and validate.

  • Paths through an association entity. A path's last segment may also be a foreign-key association that isn't a declared relation, such as the far side of a pivot's association entity. WhereThroughIn::make('definition', 'placeholderRows.definition') walks the template's OneToMany to its pivot rows and compares IDENTITY(row.definition) with the requested ids, bound with the definition id's Doctrine type. A segment may also name a pivot belongsToMany the entity has no Doctrine association for: WhereThroughIn::make('placeholder', 'placeholders'), WhereThrough::make('placeholderName', 'placeholders.name') and WhereHas::make('hasPlaceholders', 'placeholders') join through the relation's association entity, found as its reads find it.

  • Values bound in their database form. A value compared with a Symfony UID column (uuid, ulid) or any column the driver binds as binary is converted with the column's Doctrine type first, and a value compared with an association with the type of the id it holds. So filter[id]=<uuid> matches a BINARY(16) id on SQLite or MySQL, on a plain column filter, a set filter and a traversal leaf alike. A value the type can't convert matches nothing. WhereIdIn, WhereIdNotIn and a Where on the id column first decode each value through the id encoder of the type the filter runs against, so a client filters by the ids it reads, and an entity two types serve decodes with the encoder of the type that was asked. A path ending on an association of an entity no relation names, such as a pivot entity's, decodes through the encoder of the type serving the associated entity. When several types serve it with different encoders, the one the filter's declaration names decides: the type the filter runs against, the related type of one of its relations, or on a relation's reads the parent type. If none of those serves it, the cache warm-up fails naming the filter and the candidate types. Types sharing an entity with the same encoder, or none, need no name. A path ending on a field that maps an association's foreign key, such as a read-only definitionId beside definition, compares as the association does. A value the encoder can't decode is compared as sent.

  • WhereHasMatching — the Doctrine-only escape hatch for what WhereThrough's single dotted comparison cannot express: a multi-column / OR / NOT predicate, or raw DQL. It lives in the bundle's haddowg\JsonApiBundle\DataProvider\Doctrine\Filter namespace (not core), with two construction surfaces:

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

public function filters(): array
{
    return [
        // A Doctrine Criteria applied (AND/OR/NOT) on the related root — structured and safe.
        WhereHasMatching::criteria('hot', 'tracks', Criteria::create()->where(
            Criteria::expr()->gt('playCount', 1000),
        )),
        // A raw-subquery closure parameterised by the request value — the deep hatch.
        WhereHasMatching::using('named', 'tracks', static function (
            QueryBuilder $sub,
            string $relatedAlias,
            mixed $value,
        ): void {
            $sub->andWhere(\sprintf('%s.title LIKE :q', $relatedAlias))
                ->setParameter('q', '%' . $value . '%');
        }),
    ];
}

Two boundaries follow from it being Doctrine-only: it is not portable — the same filter[hot] key is undeclared on the in-memory provider, so a request there is a clean 400 (the unrecognised-filter boundary, exactly like a pivot key), never a silent non-match — and it is not value-validated (the author owns the value: it is consumed by the closure, not compared by a declared operator, so constraints() returns []). Reach for it only when WhereThrough cannot express the predicate.

See relationships.md for relationship-endpoint context.

Sort translation to DQL

DoctrineSortHandler translates only SortByField. Directives arrive most significant first (one composite call) and append as sequential addOrderBy terms, so the request's first sort field is the primary key, as the spec requires. The - descending prefix is resolved by the shared CriteriaApplier and arrives as a per-directive descending flag.

Anything computed or multi-column has no generic DQL translation. A directive whose sort is not a SortByField is delegated to a registered DoctrineSortArmInterface; if none supports it, core's UnsupportedSort is raised.

A sort family never reaches the handler. ?sort=value.cap is matched by core's SortMatcher, the family resolves cap with the request, and the handler sees the sort it returned: a SortByField translates as above, anything else goes to its arm like any custom sort. The same matching runs for the primary collection, related and relationship endpoints, relatedQuery[<path>][sort] and cursor pages.

A SortByField declared with ->through() left-joins each to-one relation of its path, once per query however many sorts share it, and orders by the leaf column of the entity the last join reaches. Each join is kept to the rows the reached type's query extensions admit, so a relation that holds nothing and a row a scope hides both leave the join null, and the row sorts as a null column does: by the platform's own order on an offset page, and as the largest value on a cursor page. On a cursor page the level selects the joined column and the cursor reads its boundary value from the query rather than from the entity's relations, so the token and the WHERE agree on scoped rows. A path through a to-many is refused at warm-up.

Source: DoctrineSortHandler.

Custom filters and sorts (the arm seam)

The built-in handlers cover the core vocabulary; for a custom FilterInterface or SortInterface of your own, register an arm — a small service the handler consults for value objects it does not recognise, before raising UnsupportedFilter/UnsupportedSort. No need to replace the whole provider.

  • A DoctrineFilterArmInterface is supports(FilterInterface): bool plus apply(FilterInterface $filter, QueryBuilder $query, mixed $value, string $alias): void — push your predicate down with andWhere, parameter-bound, on $alias. The arm is handed the live $query rather than a pre-allocated placeholder name, so you own placeholder uniqueness: a fixed name like :value collides — silently overwriting an earlier binding — when the filter runs more than once in a request or binds more than one parameter. Derive the name off the running parameter count, the same way the built-ins do, and stay clear of the reserved jsonapi_ prefix (see Column safety).
  • A DoctrineSortArmInterface is supports(SortInterface): bool plus apply(SortInterface $sort, QueryBuilder $query, bool $descending, string $alias): void — append your term with addOrderBy (never orderBy, which would discard earlier directives).

Both interfaces are autoconfigured — register the service and the handler picks it up, exactly like a DoctrineExtension. The built-ins always win; an arm is a fallthrough, so it never shadows Where/SortByField.

// A custom filter: `filter[titleContains]=…` → WHERE LOWER(resource.title) LIKE …
final class TitleContainsArm implements DoctrineFilterArmInterface
{
    public function supports(FilterInterface $filter): bool
    {
        return $filter instanceof TitleContains;
    }

    public function apply(FilterInterface $filter, QueryBuilder $query, mixed $value, string $alias): void
    {
        // Derive a collision-free placeholder off the running parameter count — the
        // SAME mechanism the built-in handler uses — so this filter can run more than
        // once in a request without one binding clobbering another. The `arm_` prefix
        // keeps clear of the handler's reserved `jsonapi_` parameters.
        $name = 'arm_' . \count($query->getParameters());
        $query
            ->andWhere(\sprintf('LOWER(%s.title) LIKE :%s', $alias, $name))
            ->setParameter($name, '%' . \mb_strtolower((string) $value) . '%');
    }
}
// Order by a to-many's size: `sort=byCount` → ORDER BY SIZE(resource.<relation>).
final class OrderByRelationCountArm implements DoctrineSortArmInterface
{
    public function supports(SortInterface $sort): bool
    {
        return $sort instanceof OrderByRelationCount;
    }

    public function apply(SortInterface $sort, QueryBuilder $query, bool $descending, string $alias): void
    {
        \assert($sort instanceof OrderByRelationCount);
        // SIZE() can't sit directly in DQL ORDER BY — select it HIDDEN and order by that.
        // Derive a DISTINCT alias per relation, so several count sorts in one request
        // don't collide — the sort twin of how the built-in handler derives unique
        // parameter names (`$sort->relation` is a validated identifier).
        $variable = 'count_' . $sort->relation;
        $query->addSelect(\sprintf('SIZE(%s.%s) AS HIDDEN %s', $alias, $sort->relation, $variable))
            ->addOrderBy($variable, $descending ? 'DESC' : 'ASC');
    }
}

A custom sort arm orders every read, including a windowed to-many. The first page of a to-many that renders with its parent, through ?include or withData(), is cut for a whole page of parents in one window-function query. A cursor-paged relation ordered by a custom sort runs that query too: the sort's keyset expression is selected for the window to order by, with nulls largest, and each parent's cursor is minted as the relation's own endpoint mints it, valueFromQuery included. A numbered or offset window has no expression to order by, so a custom sort there is read with one bounded query per parent, as window_functions: false reads every relation, and so is a keyset expression the window query can't take. A custom filter arm composes on every path.

For a portable custom filter/sort that must also run on the in-memory provider (the conformance witness), ship the in-memory twin too — an ArrayFilterArmInterface (a row predicate) or ArraySortArmInterface (a per-row sort key) — passed to the InMemoryDataProvider constructor (it is hand-built, so its arms are not DI-tagged). An inherently Doctrine-specific filter (a raw-DQL scope) ships only the Doctrine arm; it is simply not declared on an in-memory resource.

Custom sorts under a cursor

A cursor page orders by a custom sort only when both halves opt in. The sort implements core's KeysetSortInterface, whose keysetValue($row) is the value a boundary row writes into the cursor token. Its arm implements DoctrineKeysetSortArmInterface, which adds one method to the sort arm:

public function keysetExpression(SortInterface $sort, QueryBuilder $query, string $alias): KeysetExpression;

It returns a KeysetExpression: the DQL the level orders and compares by, and the DBAL type the boundary value binds with. The arm may add joins and parameters to $query first. The provider asks once per query and builds the level the way it builds a column's: a null flag ordered first so a null sorts as the largest value, the expression in the level's direction, and the same null-aware keyset WHERE. On a cursor page keysetExpression() replaces apply(); on every other page apply() runs as before. The arm is registered like any sort arm, since the interface extends DoctrineSortArmInterface.

Here campaigns are sorted by a placeholder value kept as text in an EAV table, so ?sort=value.cap has to cast it to compare numerically:

use Doctrine\DBAL\Types\Types;
use haddowg\JsonApi\Resource\Sort\KeysetSortInterface;
use haddowg\JsonApi\Resource\Sort\SortFamily;

// The resource: a family resolving `value.<placeholder>` to the sort below.
public function sorts(): array
{
    return [
        SortFamily::make('value', fn(string $suffix, JsonApiRequestInterface $request): ?SortInterface
            => $this->placeholders->exists($suffix) ? new PlaceholderValueSort('value.' . $suffix, $suffix) : null)
            ->withSuffixPattern('[a-z_]+'),
    ];
}

final readonly class PlaceholderValueSort implements KeysetSortInterface
{
    public function __construct(public string $key, public string $placeholder) {}

    public function key(): string
    {
        return $this->key;
    }

    // What the cursor token carries: the same number the SQL compares.
    public function keysetValue(mixed $row): ?int
    {
        $value = $row->placeholderValue($this->placeholder);

        return $value !== null ? (int) $value : null;
    }
}

final class PlaceholderValueSortArm implements DoctrineKeysetSortArmInterface
{
    public function supports(SortInterface $sort): bool
    {
        return $sort instanceof PlaceholderValueSort;
    }

    public function apply(SortInterface $sort, QueryBuilder $query, bool $descending, string $alias): void
    {
        $query->addOrderBy($this->keysetExpression($sort, $query, $alias)->dql, $descending ? 'DESC' : 'ASC');
    }

    public function keysetExpression(SortInterface $sort, QueryBuilder $query, string $alias): KeysetExpression
    {
        \assert($sort instanceof PlaceholderValueSort);
        $join = 'placeholder_' . $sort->placeholder; // the suffix pattern keeps it an identifier

        $query
            ->leftJoin(PlaceholderValue::class, $join, 'WITH', \sprintf('%1$s.campaign = %2$s AND %1$s.name = :%1$s_name', $join, $alias))
            ->setParameter($join . '_name', $sort->placeholder);

        return new KeysetExpression(\sprintf('CAST_INTEGER(%s.value)', $join), Types::INTEGER);
    }
}

DQL has no CAST, so the application registers one, here as CAST_INTEGER, under doctrine.orm.dql.numeric_functions. The bundle's own test suite has a short FunctionNode that emits CAST(<expr> AS INTEGER); a library such as beberlei/doctrineextensions ships portable ones. A LEFT JOIN matters: a campaign with no cap row yields null and sorts last ascending, first descending, and keeps its place in the page.

The rules for the expression and its type:

  • The expression is any scalar DQL: a field path (placeholder_cap.amount), a DQL function call, CASE, COALESCE, NULLIF, arithmetic, or a subquery in parentheses. A field path is ordered and tested for null in place, like a column. Anything else is selected AS HIDDEN with its null flag and ordered by those result variables, and the keyset tests it for null by comparing it with itself, since DQL takes IS NULL after little more than a path or a function. The expression also sits in WHERE, so it can't be an aggregate over the query's own rows; a subquery that aggregates is fine.
  • The keyset writes the expression in several places, and DQL refuses an identification variable declared twice in one query. An expression that declares its own, such as a subquery's FROM Member m, is built with KeysetExpression::repeatable(), whose closure takes a suffix to add to each variable it declares. A join the arm adds to $query is declared once, so an expression over it needs no suffix.
  • By default the cursor token carries keysetValue(), and the next page compares the expression against it, so the two must agree. Pass valueFromQuery: true and the provider selects the expression and writes the boundary row's selected value into the token instead, for a value PHP can't compute from the entity, such as a count from a subquery. keysetValue() still orders the sort on the in-memory provider.
  • The value arrives back in its token form: a DateTimeInterface as an RFC 3339 string with microseconds, a Stringable as its string, a backed enum as its value. $type null binds that token value as is. A date or date-time type parses it back to the PHP date class the type converts. A naive datetime or datetime_immutable type also moves it into PHP's default timezone, the zone Doctrine stores and reads those columns in, since keysetValue() may report a date-time in any offset. A datetimetz or date type keeps the value's own offset or day. Any other type binds the value with that type. A value read from the query is converted with $type before it goes into the token.

Here teams sort by their best member's score, which only the member table knows:

public function keysetExpression(SortInterface $sort, QueryBuilder $query, string $alias): KeysetExpression
{
    return KeysetExpression::repeatable(
        static fn(string $suffix): string => \sprintf(
            '(SELECT MAX(member%1$s.score) FROM %2$s member%1$s WHERE member%1$s.team = %3$s)',
            $suffix,
            Member::class,
            $alias,
        ),
        Types::INTEGER,
        valueFromQuery: true,
    );
}

A cursor-paged collection checks its declared sorts at cache:warmup. A custom sort that does not implement KeysetSortInterface, or whose Doctrine arm does not implement DoctrineKeysetSortArmInterface, fails the build with a message naming the type, the sort and the fix. That covers the type's own collection and every to-many whose related collection pages by cursor. A sort family resolves its sorts per request, so a family that resolves to such a sort is still a 500 UnsupportedSort when a request uses it. A cursor-paginated include or withData() linkage ordered by a custom sort cuts its first page in the shared window query, as described above, and its next link pages on through the relation's endpoint. The in-memory provider needs no arm for the cursor itself; it orders a cursor page by keysetValue() directly.

Self-applying filters: no arm to register

For a one-off, dependency-free Doctrine filter, skip the separate arm service and put the query fragment on the filter VO itself by implementing AppliesToQueryBuilder:

final readonly class Active implements AppliesToQueryBuilder
{
    public function key(): string { return 'active'; }
    public function constraints(): array { return [(new Boolean())]; }

    public function applyToQueryBuilder(QueryBuilder $query, mixed $value, string $alias): void
    {
        $query->andWhere(\sprintf('%s.archivedAt IS NULL', $alias)); // a named scope, a Criteria, raw DQL…
    }
}

The handler consults it before the arm registry, so it runs with no DoctrineFilterArmInterface registered — the self-applying twin of the arm seam, and the query counterpart of the NativeConstraints validation carrier. Reach for an arm instead when the application needs injected services (a Security, a repository). Like a raw-DQL arm it is Doctrine-only — the key is undeclared on the in-memory provider, so a request there is a clean 400. Bind the request value as a parameter (never interpolate it), deriving a collision-free name off the running parameter count, clear of the reserved jsonapi_ prefix.

Describe a custom filter in the OpenAPI document. A custom FilterInterface with no value constraints projects a plain string filter[…] parameter with a generic description — accurate, but nothing a reader learns from. Two opt-in core interfaces fix that, and a custom filter gets neither by accident:

  • DescribedFilter (getDescription(): ?string) gives the parameter its own prose — the same hook the convenience filter library uses.
  • DescribesQueryParameter declares the parameter envelope: the value schema plus the OAS style/explode for a structured wire shape, so a nested object or comma-list documents as a deepObject or array rather than a scalar. A scalar custom filter wants it whenever its value is narrower than core can work out — core types an unconstrained filter's value from the single column it targets, and a filter targeting several columns (or none) falls back to the string a query parameter is on the wire. The example's FullTextSearch searches several columns and declares that string itself, which is what the fallback would have given it — the declaration starts earning its keep the moment the wire shape stops being a plain scalar.

(Built-in and Where/Range-derived filters already self-describe.)

Column safety

Filter and sort columns come from the server-side resource declaration, never from the client (the client supplies only the declared filter key / sort field name). Before interpolation, each column is regex-validated as a DQL field path — ^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$, dots allowed for embedded fields — so a declaration typo fails loudly rather than reaching the DQL parser interpolated. Values are always bound as query parameters, and every generated placeholder/scope parameter is prefixed jsonapi_ (collision-free; reserved — a query extension must avoid that prefix).

For a related to-many endpoint (GET /{type}/{id}/{rel}), the provider's fetchRelatedCollection scopes the related entity's query to the parent without loading the whole collection — so ?filter/?sort/?page apply against the related type's vocabulary, and pagination windows in SQL. There are two branches:

  • FK fast-path — a single-valued inverse association (the OneToMany case, where the related entity carries the owning foreign key). Scoped directly by that FK. In the example, albums.tracks takes this path: Track carries the owning album reference, so the related-track query is WHERE resource.album = :parent.
  • IN-subquery — any other to-many (owning-side, or many-to-many on either side). Scoped by an IN subquery rooted on the parent that keeps the related entity as the outer query root, so the shared filter/sort/count/window machinery applies identically. In the example, playlists.tracks (a many-to-many — see Track / Playlist) takes this path.

The RelatedCollectionTest exercises both branches plus an unpaginated baseline, and proves the related collection filters/sorts against the related vocabulary (a tracks default filter even hides the explicit track from GET /albums/1/tracks). The relationship-endpoint behaviour around these collections — paginated defaults, linkage rendering — is on relationships.md.

The polymorphic boundary

A polymorphic to-many (MorphToMany, whose relatedTypes() spans more than one type) is a deliberate hard boundary: the Doctrine provider executes one scoped query against a single related entity class, and a polymorphic collection's members span entity classes, so there is no single query to run. fetchRelatedCollection throws a \LogicException for it, and its message points at the two ways past it below.

A MorphToMany declared with identifiedBy() doesn't reach that boundary either. It reads its members' type and id pairs off the parent and loads each type's rows by id through that type's provider, so the related endpoint, ?withCount and ?include all work on Doctrine; see relationships → a MorphToMany stored as type and id rows.

A MorphToMany with extractUsing() doesn't reach that boundary. Its related endpoint and ?withCount page and count the closure's value in memory, whether or not any of its types has an extension, so it needs no custom provider.

A host that needs a polymorphic to-many supplies a custom provider that resolves the members across types. The example app does exactly this: LibraryItemsProvider serves GET /libraries/{id}/items (a MorphToMany over tracks/albums/artists — see LibraryResource) by resolving each member through its per-type repository. See custom-data-providers.md for the recipe and relationships.md for the polymorphic rendering — link core relations for MorphToMany itself.

belongsToMany pivot data

When a belongsToMany relation declares pivot fields — as real field definitions, ->fields(Integer::make('position'), DateTime::make('addedAt')->readOnly(), …) — the Doctrine provider reads those join-table values and exposes them: rendered as per-member meta.pivot, sortable as a zero-config ?sort vocabulary on the related endpoint (?sort=position auto-derives from the field), and — writable by default — settable from the linkage meta.

A pivot filter, by contrast, is author-declared, not auto-derived. To filter on a pivot column, add a Where (or any value filter) to the relation's withFilters() whose target column is pivot.-prefixed:

BelongsToMany::make('orderedTracks', 'tracks')
    ->fields(Integer::make('position'), Integer::make('weight'))
    ->withFilters(
        Where::make('position', 'pivot.position')->integer(),   // filter[position] on the join column
        Where::make('weight', 'pivot.weight')->integer(),
    ),

— from the example's PlaylistResource::orderedTracks. The pivot. column prefix routes the filter to the join alias (the cast is auto-resolved from the backing pivot field); the wire filter[<key>] key is whatever you name, independent of the column. The relation's withFilters()/withSorts() and the pivot. convention are covered on relationships → pivot data.

Stored pivot data only exists over an association entity. A plain #[ORM\ManyToMany] join table holds only the two foreign keys; Doctrine cannot map a position column on it. A relation whose pivot fields are all computed, or that declares none, reads that plain join table and runs no pivot query, unless it names an association entity with ->through(): then it reads and writes that entity's rows, with or without pivot fields. So a pivot relation must be backed by an association entity — Playlist -> OneToMany -> PlaylistTrack(position, addedAt) -> ManyToOne -> Track. The provider auto-detects that entity from your metadata (PivotAssociationResolver: the one to-many on the parent whose target also has a ManyToOne to the far type), or honours an explicit ->through(PlaylistTrack::class) when auto-detection is ambiguous (two candidate entities) or finds none — in which case it throws a \LogicException naming the relation. The entity's ManyToOne to the parent is the parent side and its ManyToOne to the far type the related side; an entity linking a type to itself is covered under relationships → a type linked to itself.

The fetch is one DQL statement over the association entity, with the far entity as the query root so the shared filter/sort/count/window machinery applies to the related vocabulary unchanged, the pivot filters/sorts applied on the joined pivot alias, and each declared field selected as a scalar that rides every row:

SELECT resource, pivot.position AS pivot_position, pivot.addedAt AS pivot_addedAt
FROM Track resource
INNER JOIN PlaylistTrack pivot WITH pivot.track = resource
WHERE pivot.playlist = :parent
  -- [AND related-entity filters on resource] [AND pivot filters on pivot.<field>]
ORDER BY -- [pivot.<field> | resource.<field>]
-- LIMIT/OFFSET

So the rendered pivot values come from the same query that scopes, filters, sorts and paginates the page — no two-stage query and no page-shortening, so pagination is correct.

An include, a withData() linkage or a relatedQuery over a page of parents runs that query once for the whole page. It scopes the join with pivot.playlist IN (:parents), selects the parent id beside the far entity and the pivot fields, and groups by parent and far member, so each parent gets the members, order and meta.pivot its own query would give, and a track on two playlists keeps each playlist's position. A windowed include wraps it in the per-parent ROW_NUMBER() window the other to-many includes use (see windowed includes), with the per-parent total from COUNT(*) OVER when the page is counted. A first cursor page, the one an include shows, is the same window ordered by the keyset, with each parent's cursor minted from its last row. A windowed include falls back to one pivot query per parent for window_functions: false, a sort written by a sort arm, or a counted cursor page.

A ?sort mixing a pivot and a related field is applied in the request's directive order across both aliases, so ?sort=position,title orders by the pivot key first and ?sort=title,position by the related key first. Under duplicate membership (the same far entity joined to the parent by more than one association row — a track at two positions), the query GROUP BYs the far id: the page returns one row per distinct member, the total is COUNT(DISTINCT), and the rendered meta.pivot is a single representative membership row (pivot meta is one value set per member, not a list).

Writing pivot fields (the association-entity diff)

A pivot field is writable unless ->readOnly(). The Doctrine persister applies a linkage's per-member meta as an association-entity diff over the same auto-detected entity (the PivotAssociationResolver), on both the relationship endpoints and a whole-resource write:

  • upsert each incoming member — find the existing association row for (parent, member); if present, update its writable pivot fields from meta in place (the reorder); if absent, create a new row (parent + member + the writable meta values; read-only fields take their server default, e.g. a #[ORM\PrePersist] timestamp);
  • on PATCH (Mode::Replace) remove the rows whose member is no longer present (full sync); on POST (Mode::Add) leave the rest; on DELETE (Mode::Remove) remove the incoming members' rows (no meta);
  • a read-only pivot field supplied in meta is never written; the values are coerced through each field's own cast, and the managed association entities are persisted/removed so the flush is storage-correct.

The meta is validated against the writable pivot fields' constraints (in the operation's create/update context) before the diff runs — a violation is a 422 pointed at the linkage meta, with no write.

Boundaries. Querying pivot rows is Doctrine-only: the in-memory provider keeps its pivot rows beside each parent without querying them, so a pivot key 400s there, while its writes store the pivot fields and its responses render them. A belongsToMany without fields() keeps the plain related-collection scoping above. See relationships.md for the resource declaration, the rendered shape and the write convention.

The load-state seam

DoctrineRelationshipLoadState powers a relation's lazy-linkage policy (wired into core through Server::withRelationshipLoadState()). A to-many and a HasOne are lazy by default; it answers, without triggering a load, whether such a relation's linkage is already in memory, so a lazy relation can omit its data member rather than force a lazy round-trip just to render identifiers:

  • a to-many is "loaded" only when its backing association is an already-initialised collection — a Doctrine PersistentCollection's isInitialized() is consulted directly (it neither iterates nor initialises); a plain array / ArrayCollection (a fresh entity or an eager fetch) counts as loaded;
  • a to-one is always loaded — a lazy ManyToOne proxy already carries its identifier, so emitting the linkage reads the foreign key off the proxy and never hits the database.

The example's albums→tracks relation relies on the lazy default — no opt-in needed:

HasMany::make('tracks', 'tracks')
    ->paginate(PagePaginator::make()->withDefaultPerPage(2)),

A relation whose column() does not name a Doctrine association on the entity (or a non-entity model the EntityManager does not manage) is treated as loaded, so the predicate never changes behaviour for a relation it cannot reason about. In non-Doctrine apps the seam is absent and core treats every relation as loaded.

Source: DoctrineRelationshipLoadState. The lazy-linkage rendering convention (and the withData() eager opt-in) is core's — link relations.

Next / see also