I'm building a filter page with Craft and Sprig. The goal is to show the amount of products for each filter. So for example if we want to filter on color we show 2 checkboxes "Red" and "Green" and I want to show the number of related products for the Red items and the related number for the green number.

The problem I'm currently encountering is that I calculate the amount of results by adding a andRelatedTo parameter to my main query. This works perfect for the first checkbox but since the second checkbox adds another andRelatedTo parameter and the previous one is still there the number will always be 0 because none of the products are both "Red" and "Green".

Is there a way to create a deep copy of the original main query so I can reuse it without polluting it with the count of the available options?

1 Answer 1


The clone function makes it possible to clone a query for multiple use.

{% set query = craft.products() %}
{% set products = clone(query).andRelatedTo(colours) %}

That answers the question, although I’m not sure it solves the underlying issue. If you want to check for any related colours, then I’d suggest passing an array into andRelatedTo.

  • @Matthias Keep a close eye on your query count/performance with this approach, as you're going to be making separate queries for every checkbox. If you end up with lots of filters the performance will suffer. Consider using a look-up table/hash map with all the values you want. Sep 4, 2023 at 13:01
  • @JamesSmith That's a valid remark. Do you have any references on how to do this?
    – Matthias
    Sep 4, 2023 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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