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

How to reference a field in a Groq query in another part of the query without using a variable passed.

6 replies
Last updated: Sep 21, 2023
I’m looking to reference a field in a groq query in another part of the query, but without using a variable passed.
I’ve got a query which gets articles based on slug, one of the fields it pulls is the ‘categoryTitle’. Now i also have a ‘relatedArticles’ query in the same query which pulls articles based if its not the slug of the hero article, ideally i want to be able to use the categoryTitle from the hero post to filter the ‘related articles’ (see screenshot below) to only get articles that have the same categoryTitle - any idea of how to do this?
Sep 20, 2023, 11:41 PM
terminology the word you’re looking for is
: https://www.sanity.io/docs/groq-joins and to grab fields from the parent query you can use
means use the parent field.
Sep 21, 2023, 1:24 AM
so in yours you’d want
category->title == ^.categoryTitle
Sep 21, 2023, 1:25 AM
or it might be
since its an inner field.
Sep 21, 2023, 1:28 AM
though that might not work. you’d probably have to move the relatedArticles into
so it can reference the individual page category.
Sep 21, 2023, 1:31 AM
because what that original query will return is a list of pages[{},{},{}] so you couldnt reference a single page category. basically this:
'pages': query...., {
    'categoryTitle': category-title,
    'relatedArticles': query... category->title == ^.categoryTitle ...
Sep 21, 2023, 1:34 AM
Hey Parker, thanks a lot for your help - i had originally used the parent selector for a join, and hadnt got it working. However after looking at your solution, i was able to adjust it to this to get it to work
Sep 21, 2023, 1:41 AM

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?