How to optimize nested reverse relations?
There’s a lot going on here. Let’s first work out the outline of your algorithm, and therefore where things could be improved.


Query and iterate memberships


Query and iterate members


Query first asset


Get asset transform





Note: Every time a transform is used, Craft first has to check whether the transform has been generated (from the docs)

As you can see, there are multiple levels of nested relations going on. You’ve mentioned using eager-loading already, but it is definitely beneficial here. One of the cool things Craft can do is eager-load nested relations.

Have you tried something like this?

{% set memberships = craft.entries({
    section: 'membership',
    order: 'cf_membershipShorthand',
    with: [
        '{relatedMembersField}.cf_ma_asset'
    ]
}) %}

{% for membership in memberships %}
    {% for member in membership.{relatedMembersField} %}
        {% set image = member.cf_ma_asset[0] ?? null %}
        {% set imageParams = { width: 30, height: 30 } %}

        {% if image %}
            {# Output image with transform #}
        {% endif %}
    {% endfor %}
{% endfor %}


Where {relatedMembersField} is the handle of your entries field.