Skip to content

Can you eager load field on an element matched by route? #14940

Closed Answered by brandonkelly
a-solaris asked this question in Q&A
Discussion options

You must be logged in to vote

There’s no need to eager-load the matched entry or its immediate relations, since none of those will be n+1 queries. But if its relations have nested relations, you can eager-load those.

{% set relatedEntries = entry.myEntriesField
  .with('myAssetsField')
  .all() %}

{% for relatedEntry in relatedEntries %}
  {% for asset in relatedEntry.myAssetsField %}
    ...
  {% endfor %}
{% endfor %}

Or in Craft 5 with lazy eager-loading:

{% for relatedEntry in entry.relatedEntries %}
  {% for asset in relatedEntry.myAssetsField.eagerly() %}
    ...
  {% endfor %}
{% endfor %}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by brandonkelly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants