Group entries by Category and then in each category by related entry field I have a channel with categories and an entries field. I need to first group all entries by their category. This is working fine.

{% set entries = craft.entries.section('publicationsChannel') %}
{% set relatedCats = craft.categories.relatedTo(entries) %}

{% for category in relatedCats %}
   {{ category.title }}

  {% for entry in relatedEntries %}
    {# this list of entries needs to be grouped by the regionCountry field #}
    {{ entry.title }} &lt;br&gt;

  {% endfor %}
{% endfor %}


However what I now need to do is take the list of entries and further organize them according to a relationship field handle regionCountry

There are only 3 entries in that channel Canada, US, UK and they need to be grouped in that order.

I can't seem to wrap my head around the logic needed to do this.

What I need finally is.


Category 1



Canada



entry 1




entry 2



US



entry 1




entry 2



UK



entry 1




entry 2



Category 2



Canada



entry 1




entry 2



US



entry 1




entry 2



UK



entry 1




entry 2
etc...
I figured this out in part with @syversen answer, but it need some tweaking

Here's the simplified working code. This 

{% set countries = craft.entries.section('countries') %}
{% set publications = craft.entries.section('publicationsChannel') %}
{% set categories = craft.categories.group('documentCategory') %}

{% for category in categories %}
{# list categories #}
  &lt;h4&gt;{{ category.title }}&lt;/h4&gt;

  &lt;ul&gt;
    {# inside categories list countries #}
    {% for country in countries %}
      &lt;li&gt;
      {{ country.title }}
        &lt;ul&gt;
          {# finally output entries that are in the category and country #}
          {% set relatedEntries = publications.relatedTo([
          'and',
          {targetElement: category},
          {targetElement: country, field: 'regionCountry'}
          ]) %}

            {% for entry in relatedEntries %}
              &lt;li&gt; {{ entry.title }} &lt;/li&gt;
            {% endfor %}
        &lt;/ul&gt;
      &lt;/li&gt;
    {% endfor %}
  &lt;/ul&gt;
{% endfor %}{# end categories #}