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.