How to get a relatedProducts array in GROQ, excluding the product itself.

14 replies
Last updated: Jan 13, 2022
For all GROQ experts here, I’m trying to do something that I thought would be easy but can’t figure it out for now.I’m trying to get a
array, with all the products of the same
productType (reference)
(i.e Seating), excluding the product itself.Any ideas on how I could achieve that?

API: 2021-06-07
Jan 12, 2022, 5:33 PM
feel like you can do a
&& __id != ^.__id
or something close
Jan 12, 2022, 5:34 PM
How about:
"relatedProducts": *[_type == "product"
   && _id != ^._id
   && productType._ref == ^.productType._ref

Jan 12, 2022, 5:38 PM
yeah i just searched my own code for my own related and the _id != ^.id is working, i do see I sometimes reference the ^.__ref not sure why (sorry slack just keeps removing the _)
Jan 12, 2022, 5:40 PM
Note that this will repeat the same products in every item, which is a bit inefficient. You can save latency and bandwidth by first fetching all the products and doing a separate query to find all products related to the first batch.
Jan 12, 2022, 5:40 PM
Perfect! thanks guys 🙌
Jan 12, 2022, 5:51 PM
user L
are you possibly suggesting a like allProducts.json you save down to static to diff against? I’ve done that for some clients probably improves query speed and non-noticable diff in the static rendering
Jan 12, 2022, 5:53 PM
i’ve actually used ricos next-plugins to do this for header/footer stuff
Jan 12, 2022, 5:54 PM
I’ve also used ricos plugins to do something similar, but I’m interested to know more
Jan 12, 2022, 5:54 PM
like imagine that query on 1000 products, vs do it once and pull related products on the client side from a lodash _find lookup or something
Jan 12, 2022, 5:55 PM
i guess if it’s a like 100 product site? maybe no big deal?
Jan 12, 2022, 5:55 PM
No, I mean doing a separate GROQ query after the one above it. It’s also possible to do two queries in one go:
  "products": ...,
  "relatedProducts": ...
There’s some additional complexity in matching products to related products, but shouldn’t be too bad. It’s also a question of trade-offs — if you have very few products, maybe it doesn’t make sense.
Jan 12, 2022, 5:56 PM
I have like 200+ products for now, but it’ll increase for sure
Jan 12, 2022, 5:57 PM
I love that chair, by the way. 🙂 Are you building a vintage furniture shop?
Jan 13, 2022, 2:16 PM
Yeah 😅
Jan 13, 2022, 3:02 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?