How to reference a field in a Groq query in another part of the query without using a variable passed.
Perfect! You need to use the parent operator (^) in GROQ. This operator lets you reference values from the parent scope when you're inside a nested query.
Here's how you'd apply it to your use case:
*[_type == "article" && slug.current == $slug][0]{
title,
categoryTitle,
// ... other fields
"relatedArticles": *[
_type == "article" &&
slug.current != ^.slug.current &&
categoryTitle == ^.categoryTitle
][0...3]{
title,
slug,
categoryTitle
}
}The key part is ^.categoryTitle - the caret (^) tells GROQ to look up to the parent scope (your hero article) and grab its categoryTitle field. Similarly, ^.slug.current references the hero article's slug so you can exclude it from the related articles.
You can even chain multiple parent operators if you need to go up multiple levels in scope - like ^.^.fieldName would go up two levels.
Important note: There was a bug with the parent operator that was fixed in API version 2021-03-25, so make sure you're using that version or later. The bug caused it to not always select the upper scope correctly.
The parent operator is really powerful for these kinds of nested queries where you need to filter based on the outer document's values. It keeps everything in a single query without needing to pass variables or make multiple requests.
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.