Get a peek at our latest innovations at Sanity Product Day on Dec 8th →

Get related items of a post in sanity by comparing category array reference with another array

By Alexander Staubo & Surjith S M

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.

groq.js

*[_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.

Contributors

Other schemas by authors