🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to fetch only the product attributes that its category lists in GROQ.

6 replies
Last updated: Aug 30, 2022
Hello. I'm in need of some (hopefully) quick GROQ help. My documents of type "category" have a list of references to documents of type "attribute". My documents of type "product" has a reference to a category and also have a list of "attributes". How can I make it so my query fetches only the product attributes that its category lists?To visualize, the query would theoretically be something like
*[_type == "product"] { "attrs": attributes[attrRef in @.category.attributeRefs] }
, but this doesn't work. Any ideas?
Aug 30, 2022, 12:34 PM
So, if I'm understanding your structure correctly:
*[_type == "product"]{
  'attributes': categories->.attributes[]
Aug 30, 2022, 5:16 PM
user M
Thanks for replying. My question is basically how to get the list of attributes from the category and only get THOSE attributes from my product, which is why I tried the "in" operator
Aug 30, 2022, 5:58 PM
Ah, I see now. You did previously mention that. You need to implement something much more complicated then! Something more along the lines of this . Just to get it kickstarted, maybe something like:
'attributes': attributes[@ in ^.category->.attributes[]]
You may or may not need the
before category.
Aug 30, 2022, 6:20 PM
user M
This is what I have so far:
*[_type == "product" && metadata.available && metadata.featured]{
  'attributes': variations[0].attributes[attribute in @.mainCategory->.featuredAttributes[]],
The important part here is that "attributes[].atribute" is the actual attr reference, whereas mainCategory->featuredAttributes is an array of attr references. This is what I've been trying so far but it's just not working whatsoever and I don't understand fully why. The list of mainCategory->featuredAttributes[] is retrieved successfully no problem, but for some reason "attribute in mainCategory->featuredAttributes[]" just doesn't work at all
Aug 30, 2022, 6:44 PM
Ok, so attributes are references to an attribute reference, not strings?
Aug 30, 2022, 6:47 PM
Oh I finally got it. The issue was trying to "in" the object itself.
attributes[attribute._ref in ^.mainCategory->featuredAttributes[]._ref]
Aug 30, 2022, 6:48 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?