<p>One improvement I think could be made is to fetch only the ID's of your hotTubs entries at the start of your code. You're only using this to get the related categories and fetching ID's is faster than fetching the actual elements. The relatedTo parameter works perfectly with ID's. So that could speed up things.
You can drop the orderBy parameter also as this doesn't have any effect there.</p>

<pre><code>{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .ids()
%}
</code></pre>

CC BY-SA 4.0
2018-11-14T15:28:11.823Z
2018-11-14T15:28:11.823Z
Tom De Smet
<p>I have come up with the following code to group entries by categories;</p>

<pre><code>{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .orderBy('price asc')
%}

{% set hotTubsCats = craft.categories()
  .group('newHotTubBrands')
  .relatedTo(hotTubs)
%}

{% block content %}

  {# Loop the categories #}
  {% for category in hotTubsCats.all() %}

    {{ category.title }}

    {# Get and loop through entries related to this cat #}
    {% set hotTubs = craft.entries.relatedTo(category) %}
    {% for entry in hotTubs.all() %}
      {% include '_includes/blocks/related-tub-new' %}
    {% endfor %}

  {% endfor %}

{% endblock %}
</code></pre>

<p>However, I wanted to check if this is the most efficient approach or if this could be improved upon?</p>

<categories><group><best-practice>
Grouping entries by category - most efficient approach
# Grouping entries by category - most efficient approach

(Asked by: username_0 on 2018-11-14)

I have come up with the following code to group entries by categories;
{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .orderBy('price asc')
%}

{% set hotTubsCats = craft.categories()
  .group('newHotTubBrands')
  .relatedTo(hotTubs)
%}

{% block content %}

  {# Loop the categories #}
  {% for category in hotTubsCats.all() %}

    {{ category.title }}

    {# Get and loop through entries related to this cat #}
    {% set hotTubs = craft.entries.relatedTo(category) %}
    {% for entry in hotTubs.all() %}
      {% include '_includes/blocks/related-tub-new' %}
    {% endfor %}

  {% endfor %}

{% endblock %}

However, I wanted to check if this is the most efficient approach or if this could be improved upon?

**Tags:** categories, group, best-practice

---

## 1 answers

### Answer by username_1 on 2018-11-14. Score: 5 | Accepted answer

One improvement I think could be made is to fetch only the ID's of your hotTubs entries at the start of your code. You're only using this to get the related categories and fetching ID's is faster than fetching the actual elements. The relatedTo parameter works perfectly with ID's. So that could speed up things.
You can drop the orderBy parameter also as this doesn't have any effect there.
{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .ids()
%}


---

