Skip to main content
edited tags; edited title
Link
carlcs
  • 36.3k
  • 5
  • 63
  • 140

Eager Loading-Loading child elements in a Multi Level Structure with lots of entriesmulti-level structure section

Source Link

Eager Loading a Multi Level Structure with lots of entries

I have a structure that looks like this:

  • Experiment ( Level 1)
  • Cages (Level 2)
  • Animals (Level 3)
  • Measurement (Level 4)

I am outputting this information into some inline JSON like so:

{% set mice = craft.entries({
    'section' : 'experiments',
    'level' : 3,
    'descendantOf' : entry.id,
}) %}

<script>
  var data = [
    {% for mouse in mice %}
    {
      "Cage": "{{ mouse.parent.title }}",
      "Mouse": "{{ mouse.title }}",
      "measurements": [
        {% for data in mouse.children.order('postDate') %}
        {
          "Date": "{{ data.postDate| date("d-M") }}",
          "Weight(g)": "{{ data.weight }}",
          "Length": "{{ data.length }}",
          "Depth": "{{ data.depth }}",
          "Tumor Volume": {{ data.tumourVolume }}
        }{% if not loop.last %}, {% endif %}
        {% endfor %}
      ]
    }{% if not loop.last %}, {% endif %}
    {% endfor %}
  ];
</script>

This is ok until entries start to increase, the TTFB begins to add up significantly - I am wondering if there is a way to eager load this sort of structure? The entries are very dynamic so caching isn't an option.

Thanks!