7

Is it possible to load reverse related elements? I mean if the elements I’m querying are the target elements?

Example:

I’m setting up a criteria model to get some categories and I also want to load the entries related to each category. I’m using a Categories field, so my categories are the target elements of those relations.

{% for category in craft.categories.group('news').all() %}
    {% set query = craft.entries.relatedTo({
        targetElement: category,
        field: 'myCategoriesField',
    }) %}

    {# Oh no, a N+1 query problem... #}
    {% set entries = query.all() %}
{% endfor %}

I could probably do it the other way around, query for the entries and eager load the categories. Then use the group filter to order everything by category. But that approach is awkward and has limitations, e.g. doesn’t play well with pagination.

1

Isn't eager loading the wrong idea here, since categories do not have a property anyway, which automatically points to entries assign to this category?

Let's take 2 samples:

Sample #1: behavior like lazy loading (one entry query per category)

{% for category in categories %}
{% set entries = craft.entries...relatedTo(category)
{% endfor %}

Sample #2: behavior like eager loading (one entry query for all categories)

{% set entries = craft.entries...relatedTo(categories)

Now the only trick is to sort the entries in a way that they are easy accessible from each category in the {% for category in categories %} loop.

Or should't Craft automatically cache the loaded categories and therefor make accessing them from the entry fast after having executed the Sample #2 query?

What I mean is that it would not become faster, only more comfortable if this eager loading was possible.

Only ideas...

| improve this answer | |
  • Can you please tell me how to do the missing step, get each group of entries related to every category? It’s not really possible without further queries, is it? I mean, you got the right set of entries there, but that doesn’t help much if we loose the relations. – carlcs Aug 21 '17 at 22:54
  • What do you mean by “categories do not have a property”? The entry to categories relationship was just picked because I though it would illustrate the reverse-relation problem clearly, as categories are usually the target elements. But the issue does actually apply to all element relationships. – carlcs Aug 21 '17 at 23:01
  • ad 1: I will try, give me some time ad 2: you are right, I just meant that it's a question of comfort and not a question of amount of queries. Coming from the src side of a relation always gives you the property containing the relation, but never from the target side. – Matthias Redl-Mann Aug 22 '17 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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