Alexander Staubo
Backend developer at Sanity.io
Suppose you have an Array Reference to Category and you want to get all posts with one of the categories listed in the current post. This is usually when you need to get related items.
*[_type == "post" && slug.current == $slug][0] {
title,
categories[]->,
"related": *[_type == "post" && count(categories[@._ref in ^.^.categories[]._ref]) > 0] | order(publishedAt desc, _createdAt desc) [0..5] {
title,
slug
}
}
// Params
// {"slug": "my-post"}
The above code will fetch all posts if one of the categories in the post matches with the current post's category array. This is mainly achived using the @ Operator.
count(categories[@._ref in ^.^.categories[]._ref]) > 0
This will give you true if any element in categories
is also in the post’s category list. If you want all to match exactly, you have to compare == count(categories)
.
TIP:
Use foo._ref
instead of foo->_id
, as it’s much faster to not join unless you need what's inside.
Backend developer at Sanity.io
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
A short snippet to filter category, tags or other document based on total referenced count.
Go to Sanity GROQ Filter category by highest reference count in other documentsSnippet for `internalLInk` Reference in GROQ and rendering it in React/Next.js frontend using Portabletext.
Go to Sanity internalLink render in React with Portable TextSanity preview component cannot access the parent/document if its inside an array or object. Using Custom Preview component, we can solve the issue.
Go to Sanity Custom Preview Component to get Parent Document