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
  • Select an option

  • Save DavidStrada/43495232341802c2ad8fea9e02efc1d3 to your computer and use it in GitHub Desktop.

Select an option

Save DavidStrada/43495232341802c2ad8fea9e02efc1d3 to your computer and use it in GitHub Desktop.

Revisions

  1. @Chrisedmo Chrisedmo created this gist Dec 11, 2016.
    39 changes: 39 additions & 0 deletions eager-loading.twig
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    {#
    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 %}