1

I have two category fields, teamCategory and articleCategories, on a news listing page that I'm trying to eager load. Problem is, when I add the eager loading it no longer outputs the categories. I should say right off that I'm not that experienced with Craft so I'm probably misunderstanding something.

From the documentation I've tried the array syntax but I'm either applying it wrong or there is a different approach for categories(?).

{% paginate craft.entries.section('news').with(['teamCategory', 'articleCategories']).limit(25) as pageInfo, pageEntries %}

{% for entry in pageEntries %} 

    {% set teamCats = entry.teamCategory[0] ?? null %}
    {% set articleCats = entry.articleCats[0] ?? null %}

    {% if articleCats|length %}
        {% for cat in articleCats %}
            {{ cat.slug }}
        {% endfor %}
    {% endif %}
    {% if teamCats|length %}
        {% for logo in teamCats %}
            {{ logo.title }}
        {% endfor %}
    {% endif %}
{% endfor %}

All the other posts that I could find were about more complex applications, I'm just looking for the basic function of eager loading a category field and then how to access it in the template.

I did try the non eager loaded syntax:

{% set teamCats = entry.teamCategory.all() %} 
{% set articleCats = entry.articleCategories.all() %}

Without eager loading that works, and I actually have another eager loaded field that I didn't include in this example (matrix) that works fine. It's just the categories that I'm struggling with.

1 Answer 1

1

Eager-loading turns relational fields into arrays of elements (i.e. the same thing that happens if you do entry.teamCategory.all()), so your use of the bracket syntax is technically correct.

The problem is that you're doing

{% set teamCats = entry.teamCategory[0] ?? null %}

...which will set the teamCats variable to the first category from the eager-loaded teamCategory field (or null, if there are no categories in the array). Essentially, this is the proper alternative to entry.teamCategory.one() when the field is eager-loaded.

Which is why your {% for %} loops doesn't output anything – you're trying to loop on a single element, not the entire array of categories.

Since the entry.teamCategory and entry.articleCats fields are already arrays, the below would work:

{% set teamCats = entry.teamCategory %}
{% set articleCats = entry.articleCats %}

...although from looking at the example you don't really need those variables, so technically you could just delete those and do {% for cat in entry.articleCategories %} and {% for logo in entry.teamCategory %}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.