Skip to content

[9.x] Fix N+1 queries when augmenting relationships - #843

Merged
duncanmcclean merged 2 commits into
9.xfrom
defer-nested-augmentation
Aug 12, 2026
Merged

[9.x] Fix N+1 queries when augmenting relationships#843
duncanmcclean merged 2 commits into
9.xfrom
defer-nested-augmentation

Conversation

@duncanmcclean

Copy link
Copy Markdown
Member

This pull request fixes an issue where augmenting a relationship would trigger an N+1 query for each of the related models' own relationships.

This was happening because toAugmentedArray resolves every Value up-front. For most Statamic data that's cheap, since resolving a relationship just returns the raw IDs. In Runway, the raw value of a relationship is $model->getAttribute($handle), which lazy loads it. So augmenting a has_many field queried every relationship on every related model, whether or not the template used them.

This PR fixes it by using toDeferredAugmentedArray instead, so each Value is only resolved when something actually asks for it. This is the same thing Statamic does when hydrating the cascade.

This PR also swaps out the same pattern in a few other places which augment a whole model just to use one or two keys:

  • The {{ runway }} tag.
  • URI generation (both on save and in runway:rebuild-uri-cache), which was loading every relationship just to parse /posts/{{ slug }}.
  • title_format on the relationship fieldtypes.

Fixes #777

duncanmcclean and others added 2 commits August 3, 2026 10:32
`toAugmentedArray` resolves every `Value`, which for a relationship means
lazy loading it, so augmenting a relationship queried each related model's
own relationships whether or not the template used them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@duncanmcclean
duncanmcclean merged commit f12a843 into 9.x Aug 12, 2026
16 checks passed
@duncanmcclean
duncanmcclean deleted the defer-nested-augmentation branch August 12, 2026 14:16
@github-actions

Copy link
Copy Markdown

Released as part of v9.6.2.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Augmentation N+1 query issue on has_many relationships

1 participant