1

I'm trying to show some Commerce 2 order information on the front-end. I can't work out the correct syntax. I'm trying to list orders that include a specific product.

I have orders for item SKU "abc123" but this is returning no results.

{% set myOrderQuery = craft.orders()
    .relatedTo("abc123")
    .limit(10)
    %}

{% set orders = myOrderQuery.all() %}

{% if orders|length %}
  <ul>
    {% for order in orders %}
      {% for item in order.lineItems %}
        <li>{{ item.sku }}</li>
      {% endfor %}
    {% endfor %}
  </ul>
{% else %}
  <p>No results</p>
{% endif %}

If I remove the .relatedTo parameter I get results including orders for that item. How do I just return orders that include that item?

I've tried various permutations of relatedTo and search but haven't found anything that works yet.

2

Use the hasPurchasable order query param:

https://docs.craftcms.com/commerce/v2/dev/element-queries/order-queries.html#haspurchasables

{% set myOrderQuery = craft.orders()
    .hasPurchasables(product.defaultVariant)
    .limit(10)
%}
  • Just what I needed, that's working. Thanks Luke – Tim Print Jun 24 '19 at 10:28

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.