How to reference parent's parsedSlug in nested GROQ query?

3 replies
Last updated: Feb 23, 2023
How could I refer the above
parsedSlug
?

*[_type == 'devCategory'] {
 		_id,
 		"level": 0,
 		"title": coalesce(title[$lang], title.en),
        "parsedSlug": slug.current,
 		"children": *[parent._ref == ^._id] {
 		  _id,
		  "level": 1,
          "slug": ^.parsedSlug + "/", πŸ‘ˆπŸ‘ˆ Here, I would get the above parsedSlug
 		  "title": coalesce(title[$lang], title.en),
 	  }
}
AI Update

Good news - you're on the right track! You can absolutely reference parsedSlug from the parent scope using the parent operator (^), but you need to adjust your syntax slightly.

In your query, you're already correctly using ^._id to reference the parent's _id field. The same pattern works for your custom parsedSlug field. Here's the corrected version:

*[_type == 'devCategory'] {
  _id,
  "level": 0,
  "title": coalesce(title[$lang], title.en),
  "parsedSlug": slug.current,
  "children": *[parent._ref == ^._id] {
    _id,
    "level": 1,
    "slug": ^.parsedSlug + "/",  // This will work!
    "title": coalesce(title[$lang], title.en),
  }
}

The key point is that ^.parsedSlug refers to the computed field from the parent document's projection (the outer query). Since you're defining "parsedSlug": slug.current in the parent scope, you can access it in the nested query with ^.parsedSlug.

The parent operator (^) lets you traverse up one level in scope. If you needed to go up multiple levels, you could chain them like ^.^.fieldName, but in your case, one caret is perfect since you're only one level deep.

One thing to be aware of: if you're using an API version before 2021-03-25, there was a bug with the parent operator that could cause unexpected behavior. If you run into issues, make sure you're on a recent API version.

Show original thread
3 replies
I believe you can use Pipeline Components , so something like:

*[_type == 'devCategory'] {
 		_id,
 		"level": 0,
 		"title": coalesce(title[$lang], title.en),
        "parsedSlug": slug.current,
 		
} | {
   ...,
   "children": *[parent._ref == ^._id] {
 		  _id,
		  "level": 1,
          "slug": parsedSlug + "/", πŸ‘ˆπŸ‘ˆ Here, I would get the above parsedSlug
 		  "title": coalesce(title[$lang], title.en),
 	  }
}
Work like a charm. Thank you
user G
awesome 😊

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?