<p>You can get the categories to display hierarchically pretty efficiently using the <a href="http://buildwithcraft.com/docs/templating/nav" rel="nofollow">{% nav %} tag</a>:</p>



<pre class="lang-html prettyprint-override"><code>{% 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;
</code></pre>

<p>Then, you can add in the related entries like so:</p>

<pre class="lang-html prettyprint-override"><code>&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;
</code></pre>

<p>That code suffers from the “<em>N</em>+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 <em>N</em>+1 SQL queries – one query to geth the initial set of categories, plus <em>N</em>, the total number of second-level categories. If you have 100 categories, that’s 101 SQL queries.</p>

<p>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 <a href="https://github.com/mdcpepper/fetch" rel="nofollow">Fetch</a> which makes it possible.  Download and install that, and then you can do the following:</p>

<pre class="lang-html prettyprint-override"><code>{% 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;
</code></pre>

CC BY-SA 3.0
2016-06-22T23:02:32.740Z
_Craft_ added [eager-loading elements](https://craftcms.com/docs/templating/eager-loading-elements) with version 2.6.2771 which means that [Fetch](https://github.com/mdcpepper/fetch) has been depreciated.
bennobo
CC BY-SA 3.0
2016-06-23T00:42:49.130Z
Craft’s built-in eager-loading support doesn’t actually help in this scenario yet though (reverse relationships).
Brandon Kelly
CC BY-SA 3.0
2015-10-19T21:39:56.453Z
2015-11-05T15:46:42.323Z
2015-11-05T15:46:42.323Z
Brandon Kelly
<p>Been trying to get this working for a few hours but no joy, hope someone can help.</p>

<p>I'm looking like an post archive of all entries.</p>

<p>Something like</p>

<ul>
<li>Category1

<ul>
<li>Sub Category 1

<ul>
<li>Entry / Entry</li>
</ul></li>
<li>Sub Category 2

<ul>
<li>Entry / Entry</li>
</ul></li>
</ul></li>
<li>Category 2

<ul>
<li>Sub Category 3

<ul>
<li>Entry / Entry</li>
</ul></li>
</ul></li>
</ul>

<p>Etc.</p>

<p>Tried with grouping and even tried with a plugin - <a href="https://github.com/timkelty/groupby-craft" rel="nofollow">https://github.com/timkelty/groupby-craft</a> But no luck so far, help greatly appreciated.</p>

CC BY-SA 3.0
2015-10-18T15:17:52.680Z
Two questions – are the categories in the same category group? And how do you want to handle entries that are in multiple categories (list each entry once, or list each entry once for every category they are in)?
Mats Mikkel Rummelhoff
CC BY-SA 3.0
2015-10-18T20:03:36.457Z
1.) Same category group - yes, 2.) Entries will only be in one category and always in a sub category (an entry would never just be in a top level category) Thanks for reply, look forward to get this working.
John Macpherson
<categories><group>
Entries grouped by Category and then Sub Category
# Entries grouped by Category and then Sub Category

(Asked by: username_0 on 2015-10-18)

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.

**Tags:** categories, group

> **Comments:**
> **username_1**: Two questions – are the categories in the same category group? And how do you want to handle entries that are in multiple categories (list each entry once, or list each entry once for every category they are in)?  
> **username_0**: 1.) Same category group - yes, 2.) Entries will only be in one category and always in a sub category (an entry would never just be in a top level category) Thanks for reply, look forward to get this working.  

---

## 1 answers

### Answer by username_2 on 2015-10-19. Score: 4 | Accepted answer

You can get the categories to display hierarchically pretty efficiently using the {% nav %} tag:
{% set categories = craft.categories.group('myGroup').find() %}


  {% nav category in categories %}
    
      {{ category.title }}
      {% ifchildren %}
        
          {% children %}
        
      {% endifchildren %}
    
  {% endnav %}


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

  ...
  {% 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 %}
      
        {% for entry in entries %}
          {{ entry.getLink() }}
        {% endfor %}
      
    {% endif %}
  {% endif %}


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') %}


  {% nav category in categories %}
    
      {{ category.title }}
      {% ifchildren %}
        
          {% children %}
        
      {% 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 %}
        
          {% for entry in category.fetched('reverse:myCategoriesField') %}
            {{ entry.getLink() }}
          {% endfor %}
        
      {% endif %}
    
  {% endnav %}

> **Comments:**
> **username_3**: _Craft_ added [eager-loading elements](https://craftcms.com/docs/templating/eager-loading-elements) with version 2.6.2771 which means that [Fetch](https://github.com/mdcpepper/fetch) has been depreciated.  
> **username_2**: Craft’s built-in eager-loading support doesn’t actually help in this scenario yet though (reverse relationships).  

---

