Skip to content

Instantly share code, notes, and snippets.

@DavidStrada
Forked from Chrisedmo/eager-loading.twig
Created September 7, 2021 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidStrada/43495232341802c2ad8fea9e02efc1d3 to your computer and use it in GitHub Desktop.
Save DavidStrada/43495232341802c2ad8fea9e02efc1d3 to your computer and use it in GitHub Desktop.
#CraftCMS: Eager-Load Nested Sets of Elements
{#
According to docs (https://craftcms.com/docs/templating/eager-loading-elements),
this is how you Eager-Load Nested Sets of Elements
#}
{% set entries = craft.entries({
section: 'news',
with: [
'entriesField.assetsField'
]
}) %}
{# And this is how you Eager-Load Elements Related to Matrix Blocks #}
{% set blocks = entry.matrixField.find({
with: ['blockType:assetsField']
}) %}
{# or #}
{% set entries = craft.entries({
section: 'news',
with: ['matrixField.blockType:assetsField']
}) %}
{#
but when you have e.g. Categories inside each Martix Block, you can't do:
`with:['matrixField.blockType:assetsField.categoriesField`…
do this separately instead:
#}
{% set entries = craft.entries({
section: 'news'
}) %}
{% for entry in entries %}
{% for block in entry.matrixField.type('assetsField').find({ with: ['categoriesField'] }) %}
{% endfor %}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment