Entries grouped by Category and then Sub Category Been trying to get this working for a few hours but no joy, hope someone can help.

I'm looking like an post archive of all entries.

Something like


Category1


Sub Category 1


Entry / Entry

Sub Category 2


Entry / Entry


Category 2


Sub Category 3


Entry / Entry




Etc.

Tried with grouping and even tried with a plugin - https://github.com/timkelty/groupby-craft But no luck so far, help greatly appreciated.
You can get the categories to display hierarchically pretty efficiently using the {% nav %} tag:



{% set categories = craft.categories.group('myGroup').find() %}

&lt;ul&gt;
  {% nav category in categories %}
    &lt;li class="category"&gt;
      {{ category.title }}
      {% ifchildren %}
        &lt;ul&gt;
          {% children %}
        &lt;/ul&gt;
      {% endifchildren %}
    &lt;/li&gt;
  {% endnav %}
&lt;/ul&gt;


Then, you can add in the related entries like so:

&lt;li class="category"&gt;
  ...
  {% endifchildren %}

  {# Are we on the second level of categories? #}
  {% if category.level == 2 %}
    {# Look for any entries that are related to this category #}
    {% set entries = craft.entries.relatedTo({
      targetElement: category,
      field: 'myCategoriesField'
    }) %}
    {# If there are any, then output them in a nested UL #}
    {% if entries|length %}
      &lt;ul&gt;
        {% for entry in entries %}
          &lt;li&gt;{{ entry.getLink() }}&lt;/li&gt;
        {% endfor %}
      &lt;/ul&gt;
    {% endif %}
  {% endif %}
&lt;/li&gt;


That code suffers from the “N+1” problem though - each 2nd level category is going to need to initiate a new SQL query to fetch the related entries. So rendering this list will require N+1 SQL queries – one query to geth the initial set of categories, plus N, the total number of second-level categories. If you have 100 categories, that’s 101 SQL queries.

To solve this, you’d need to “eager-load” the related entries. Craft doesn’t support that of the box, but Mike Pepper has a nice little plugin called Fetch which makes it possible.  Download and install that, and then you can do the following:

{% set categories = craft.categories.group('myGroup').find() %}
{% do craft.fetch.entries(categories, 'reverse:myCategoriesField') %}

&lt;ul&gt;
  {% nav category in categories %}
    &lt;li class="category"&gt;
      {{ category.title }}
      {% ifchildren %}
        &lt;ul&gt;
          {% children %}
        &lt;/ul&gt;
      {% endifchildren %}

      {# Are we on the second level of categories, and are there any related entries? #}
      {% if category.level == 2 and
            category.fetched('reverse:myCategoriesField')|length %}
        &lt;ul&gt;
          {% for entry in category.fetched('reverse:myCategoriesField') %}
            &lt;li&gt;{{ entry.getLink() }}&lt;/li&gt;
          {% endfor %}
        &lt;/ul&gt;
      {% endif %}
    &lt;/li&gt;
  {% endnav %}
&lt;/ul&gt;