How do I display entries, grouped by distinct categories where the entries share a relationship to both the category and an entry in another channel I have 2 channels:survivors, survivorContent and a Category:themes. Relationships are as follows:
survivorContent has -> related themes (max 3) AND survivorContent has -> related survivors (max 1)

Themes are always only one level deep.

I have a template that receives survivor.slug as a variable (based on a route). Given the survivor slug, I need to show a list of distinct themes that are indirectly related to this survivor (via the survivorContent->survivor relationship and the survivorContent->themes relationship). Then I need to show the survivorContent entries under each of those filtered themes that are related to both that theme and the given survivor to get output like this:


Survivor.title

Related Theme 1



Related survivorContent1 (related to both the Survivor &amp; Theme 1)




Related survivorContent2 (related to both the Survivor &amp; Theme 1)



Related Theme 2



Related survivorContent3 (related to both the Survivor &amp; Theme 2)




Related survivorContent1 (related to both the Survivor &amp; Theme 2 as well as Theme 1, above)



etc...



I'm struggling to find a way to do this that is remotely efficient. Any ideas?
Set up a criteria model with both of your relatedTo conditions and add the hierarchy to the list of returned entries using Craft's group filter.

{% set relatedEntries = craft.entries({
    section: 'survivorContent',
    relatedTo: [
        'and',
        {targetElement: entry.themesField},
        {targetElement: entry.survivorsField}
    ]
}) %}

{% set relatedEntriesGrouped = relatedEntries|group('themesField.first().title') %}

{% for title, entries in relatedEntriesGrouped %}
    {{ title }}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}
{% endfor %}


In case you don't have a "max. 1 element" limit set on your relationship fields, you might also want to look into something like the following.

{% for theme in entry.themesField %}

    {% set relatedEntries = craft.entries({
        section: 'survivorContent',
        relatedTo: [
            'and',
            {targetElement: theme},
            {targetElement: entry.survivorsField}
        ]
    }) %}

    {% if relatedEntries|length %}
        {{ theme.title }}
        {% for entries in relatedEntries %}
            {{ entry.title }}
        {% endfor %}
    {% endif %}

{% endfor %}