Reputation: 382
I have a blog with sanity CMS and I want to request related posts depending on corresponding tags from the current post which means I have to compare two arrays of tags.
My tags are described in post schema this way:
{
name: 'tags',
title: 'Tags',
type: 'array',
of: [{type: 'string'}],
options: {
layout: 'tags'
}
},
I went with the following GROQ query which is a good start I guess but obviously it doesn't work:
*[_type == "post" && slug.current == $slug][0] {
title,
tags,
"sameTags": *[_type == "post" && slug.current != $slug && count(tags in ^.tags) > 0]
}
What I would translate my query to is: "I want to get related posts which have a different slug and that own at least one tag also owned by the current post"
Upvotes: 1
Views: 874
Reputation: 3365
The count trick should work, but since you are comparing multiple tags against multiple tags, you need to iterate over them:
count(tags[@ in ^.^.tags]) > 0
In other words, it filters the tags by whether each tag appears in the other list. The additional ^.
should be needed here, as the filter introduces a new scope.
Upvotes: 3