Skip to content

Eager loading for resources mapped to an entity through stateOptions (DTO output) #8765

Open

Description

@simondaigre

Description

When a resource is a DTO backed by an entity through stateOptions: new Options(entityClass: ...), EagerLoadingExtension doesn't join any of the relations the DTO exposes. Each item then loads its relations lazily, which causes N+1 queries.

I understand that eager loading relies on serialization groups by design: apply() returns early without groups or attributes since #2002, to avoid recursive joins, and #5062 settled on documenting this rather than changing it. That makes sense for a resource that is the entity itself, where groups are the only way to tell which relations will be serialized.

A mapped resource is different: its class already describes the exact shape of the response. It usually needs no serialization groups, and adding some only to trigger eager loading duplicates that shape. Two things currently prevent the extension from using it:

  1. Without groups, apply() returns early, so nothing is joined, even with forceEager: true (the default).
  2. With groups or attributes, joinRelations() reads the property metadata of the entity ($propertyMetadataFactory->create($entityClass, $association)), not that of the resource. #[ApiProperty(readableLink: true)] on the resource's properties is therefore ignored. The entity's to-one relations get readableLink: null, so the extension stops after the first level.

The workarounds are:

  • to put API Platform metadata on the entity itself, which is what stateOptions is meant to avoid;
  • to declare a normalizationContext attributes tree that duplicates the resource class. The serializer also applies that tree, so it silently drops any field missing from it.

On our project (API Platform 5.0.5, Doctrine ORM 3), a paginated sub-collection of 30 items like the one below runs 167 queries where 10 would be enough: one query per item for the to-one relation, plus the to-many collections of each item.

This looks like the same kind of gap as #8185, fixed in fcfaf38 for nested property filters on mapped resources.

Example

#[ApiResource(
    operations: [
        new GetCollection(
            uriTemplate: '/libraries/{uuid}/books',
            uriVariables: ['uuid' => new Link(toProperty: 'library', fromClass: LibraryOutput::class)],
            provider: BookProvider::class, // Doctrine CollectionProvider + entity → DTO mapping
        ),
    ],
    stateOptions: new Options(entityClass: Book::class),
)]
final readonly class BookOutput
{
    public function __construct(
        public string $uuid,
        public string $title,
        #[ApiProperty(readableLink: true)]
        public AuthorOutput $author, // AuthorOutput embeds country (to-one) and awards (to-many)
        /** @var list<ReviewOutput> */
        #[ApiProperty(readableLink: true)]
        public array $reviews,
    ) {
    }
}

Current behavior: the page query selects only Book. Then author, its country and awards, and the reviews are loaded one book at a time.

Expected behavior: when the operation has stateOptions with an entityClass, the extension builds its join tree from the resource's property metadata instead of requiring groups. It follows the properties embedded with readableLink (or fetchEager), recursively through the embedded resources, and applies that tree to the entity's associations with the same names. The tree is bounded by what the resource embeds, which avoids the unbounded recursion that motivated #2002.

When the resource is mapped with the ObjectMapper (#[Map(source: ...)]), the same mapping could translate renamed properties into association names. We haven't checked whether ObjectMapperProvider has the same limitation, but it goes through the same Doctrine provider and extensions.

Would you accept such a change? If so, we can open a PR.

Activity

  1. philpichet commented on Oct 27, 2026

    @philpichet
    Contributor

    Hi! I measured the case you hadn't checked: a DTO resource mapped with the ObjectMapper, set up as in the DTO docs (stateOptions + #[Map(source: ...)], no custom provider). It has the same limitation.

    Setup: API Platform 5.0 (branch 5.0 at 0139548), Symfony 7.4, Doctrine ORM 3, SQLite. The model matches yours: Book → author (→ country to-one, awards to-many) and reviews (to-many). The data has 30 books, 10 authors, 5 countries, 2 awards per author and 3 reviews per book.

    #[ApiResource(
        shortName: 'BookDto',
        operations: [new GetCollection(uriTemplate: '/dto/books'), new Get(uriTemplate: '/dto/books/{id}')],
        stateOptions: new Options(entityClass: Book::class),
    )]
    #[Map(source: Book::class)]
    final class BookOutput
    {
        public int $id;
        public string $title;
        #[Map(transform: [self::class, 'mapAuthor'])] // AuthorOutput: name, country (CountryOutput), awards
        public AuthorOutput $author;
        /** @var list<ReviewOutput> */
        #[Map(transform: [self::class, 'mapReviews'])]
        public array $reviews = [];
        // ...
    }

    Results for GET ?itemsPerPage=30, counting SQL queries with a DBAL logging middleware:

    Queries
    A. Book entity as the resource, with normalizationContext groups 3 (count, ids, data with LEFT JOINs)
    B. BookOutput DTO resource mapped with the ObjectMapper 57
    B + the joins EagerLoadingExtension could build from BookOutput (added by a test extension) 3

    The 57 queries in B break down as follows:

     1 x COUNT book + 1 x book    the page
    10 x author                   one per distinct author (lazy to-one)
     5 x country                  one per distinct country
    10 x award                    one awards collection per author
    30 x review                   one reviews collection per book
    

    The three cases return the same data. So ObjectMapperProvider goes through the same Doctrine provider and extensions, and gets nothing joined because the operation has no groups. Once the joins are in the query, the mapping only reads already loaded relations: no extra queries, no change needed on the ObjectMapper side.

    This supports building the join tree from the resource class when stateOptions has an entityClass, as you suggest. For mapped resources, the join tree would also have to follow #[Map(source: ...)] renames to find the association names.

    Happy to test a PR against this setup, or to work on the PR if you don't have time.

  2. soyuka commented on Nov 3, 2026

    @soyuka
    Member

    Thanks for the detailed report and the numbers @simondaigre @philpichet! We're in favor of loading the associations from the resource's metadata when there's an entityClass, the groups requirement makes little sense for a mapped resource.

    I'm not a huge fan of matching the entity associations by name though, it works until someone renames a property and then it silently stops joining. Maybe the ObjectMapper metadata can help us find the mapped association (#[Map(source: ...)]), but with a transform like mapAuthor we have no idea what is actually read on the entity. This is rather complicated and I'm not sure yet what the best approach is.

    I think the best way to move forward is to start with functional tests that count the queries, so that we can compare approaches against the same cases:

    • stateOptions + custom provider, no groups, to-one and to-many embedded with readableLink
    • nested embeds (author -> country / awards)
    • ObjectMapper with #[Map(source: ...)] renaming an association
    • ObjectMapper with a transform on the relation
    • a resource without embeds, which should not join anything

    @philpichet your setup already covers most of these, a PR with only the tests (failing) would be really nice, then we can discuss the implementation there. Thoughts?

  3. philpichet commented on Nov 11, 2026

    @philpichet
    Contributor

    Thanks @soyuka! I opened #8836 with the tests only, failing on purpose, against 4.4. It covers the five cases you listed, on the same entities (6 books, 3 authors, 2 countries, 2 awards per author, 2 reviews per book). Each test checks the response body and the number of SQL queries:

    Case Now Expected
    Custom provider, to-one + to-many with readableLink 10 2
    Custom provider, nested embeds (author → country / awards) 9 2
    ObjectMapper, #[Map(source: ...)] renaming the associations 16 3
    ObjectMapper, transform on the relations 16 3
    No embed (passes today) 2 2

    The expected counts are those of a page query that joins every embedded relation, plus the paginator's DISTINCT ids and COUNT queries. The PR description has the details, and a question about the transform case: should it be a target or a documented limitation?

    Note: the CI on the PR doesn't reach the tests yet. composer refuses mcp/sdk 0.8 because of the PKSA-s52d-n7sx-trsg advisory, and the latest push on 4.4 fails the same way. The results above are from a local run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions