Which is the least CPU intensive (SQL-intensive) way to get the sum of products that are relatedTo a category?

Like this?

{% set productCount = craft.products.relatedTo(category)|length %}

  • As far as I am aware, yes. Feb 28, 2020 at 16:47

1 Answer 1


When you call the |length twig filter you are implicitly treating the element query as an array. This behaviour was depreciated in Craft 3, and also results in a DB query being sent that is equivalent to .count() (Craft 3) or .total() (Craft 2).

To remain up to date, while still minimising SQL load for your page: either call the relevant command (.count(), .total()):

{% set productCount = craft.products.relatedTo(category).count() %}

Or, if you're going to be doing a full (limit: null) query at some point anyway, do that now and then use the length filter:

{% set products = craft.products.relatedTo(category).limit(null).all() %}
{% set productCount = products|length %}
  • Thanks for the explanation Nick.
    – nitech
    Mar 2, 2020 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.