Managed to solve this.
First, I've added a categories field to the order form.
On the checkout page I loop over all lineItems in the cart and collect the category id's like this.
{% set categoryIds = [] %}
{% for item in cart.lineItems %}
{% set categories = item.purchasable.product.productGroup.leaves().all()%}
{% for category in categories %}
{% if category.id not in categoryIds %}
{% set categoryIds = categoryIds|merge([category.id]) %}
{% endif %}
{% endfor %}
{% endfor %}
Then, I submit the categories using a hidden input.
{% for catId in categoryIds %}
<input type="hidden" name="fields[productGroup][]" value="{{ catId }}">
{% endfor %}
Now I have categories assigned to an order and can easily filter them using .relatedTo()
, like this:
{% set ordersQuery = craft.orders().relatedTo(...) %}