GROQ query not filtering posts by category reference correctly

6 replies
Last updated: Aug 15, 2023
*[_type == "category"]{
    _id,
    title,
    "post": *[_type == "post" && category._id == ^.categories._ref]
  }
I am trying to get all post that are in a category. The code above is retrieving all categories as expected. and from the post key I am getting date. The problem is that the post key is showing all post regardless if they are in the category. I only want it to show the post in that category. Is there a way to do this. I am using the default blog schema
AI Update

I can see the issue with your query! The problem is in your filter condition within the subquery. You're comparing category._id (from the post) with ^.categories._ref, but the correct path should be ^._id to reference the parent category's ID.

Here's the corrected query:

*[_type == "category"]{
  _id,
  title,
  "post": *[_type == "post" && references(^._id)]
}

The references() function is actually the cleanest way to handle this. It will find all posts that have a reference to the current category's ID.

Alternatively, if you want to be more explicit about the field path, you can use:

*[_type == "category"]{
  _id,
  title,
  "post": *[_type == "post" && category._ref == ^._id]
}

The key issues with your original query were:

  1. You used category._id instead of category._ref - references store the ID in a _ref property
  2. You used ^.categories._ref which doesn't exist on the category document - you just need ^._id to access the parent category's ID

The ^ operator allows you to access the parent scope within the subquery, so ^._id refers to the category's _id that you're currently iterating over in the outer query.

If you want to return additional fields from the posts, you can expand the projection:

*[_type == "category"]{
  _id,
  title,
  "posts": *[_type == "post" && references(^._id)]{
    title,
    slug,
    publishedAt
  }
}
Show original thread
6 replies
Maybe you can try using
references()
:
"post": *[_type == "post" && references(^._id))
You can find an example
here .
That worked great. I feel I have a lot to learn. Is there a query generator
Glad that the solution worked for you :) I am not aware of any query generators unfortunately.For learning purposes, you can also take a look at the
GROQ arcade in addition to the Vision plugin and GROQ in 45 min .
I was able to get the same result using openai
using sanity groq how do you retrieve all posts from a certain category
followed up by
do this for every category
it returned that exact query Urvashi shared.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?