Can you eager load field on an element matched by route? #14940
-
Eager loading is a must-have in any site, no matter the complexity, but I was wondering how to deal with eager loading, when the element is matched by routing. Say I have an Entry with multiple element custom fields, often relating more elements with their own relations. In a template matched by a route, the element is supplied via Is it possible or feasible to tap into this process? Or is the best approach to take take the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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 %} |
Beta Was this translation helpful? Give feedback.
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.
Or in Craft 5 with lazy eager-loading: