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

Help with GROQ join in Sanity.io for searching products by category.

15 replies
Last updated: Feb 15, 2021
Hello! I'm new here and am learning Sanity for a job I just got. I've been messing with the default ecommerce dummy data and am having a lot of trouble doing a GROQ join. Basically I am trying to search for a product with a category name, something like this but I am sure I am quite off base what I've tried so far. Thanks for any help 🙂
*[ _type == "product" ]{
  "categories": *[ _type == "category" && ^._id in product[]._ref && slug.current == "swedish"],
Feb 15, 2021, 10:15 PM
Welcome M M! When I’m trying more complex GROQ queries, I will usually try to simplify them to isolate the bit that isn’t working for me. In your example, I would try each of the three parts of the
filter on its own to see what works and what doesn’t.
Are you comfortable using Vision for testing?
Feb 15, 2021, 10:18 PM
For example, when you run this do you get data back?

*[ _type == "product" ]{
  "categories": *[ _type == "category"],

Feb 15, 2021, 10:19 PM
Hey Geoff! Yes I am using vision right now, have been at this for a bit haha. I am just a jr dev so I am comfortable with basic SQL joins but still relatively fresh haha
Feb 15, 2021, 10:19 PM
I get back all my products when I do that query!
Feb 15, 2021, 10:20 PM
so now I need to be able to search my categories table for the slug.current or title
Feb 15, 2021, 10:21 PM
Perfect. I’m wondering about that last bit—`slug.current == 'swedish'`—since the slug will normally be specific to one document.
Feb 15, 2021, 10:21 PM
Rather than typing it in GROQ, what are you hoping for your query to do?
Feb 15, 2021, 10:22 PM
well I am doing various search features for my product list
Feb 15, 2021, 10:23 PM
I have a category select drop down menu that displays dynamically from my getinitialprops in next and was hoping to filter by category
Feb 15, 2021, 10:23 PM
If you remove
&& slug.current == "swedish"
how close do you get to your desired result?
Feb 15, 2021, 10:28 PM
It doesn't, I believe it needs to reference category id somewhere and then search for the category title/slug
Feb 15, 2021, 10:30 PM
*[ _type == "category" && slug.current == "japanese"]{
  "products": *[ _type == "product" && references(^._id) ]
Feb 15, 2021, 10:39 PM
I finally got it 🙂
Feb 15, 2021, 10:39 PM
thanks so much for helping me Geoff! Loving Sanity so far, it is really powerful
Feb 15, 2021, 10:40 PM
Excellent! Nice work! 🙌
Yes, it sure is! Enjoy your time with it!
Feb 15, 2021, 10:41 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?