Updated on: Sun Dec 20 2020
Sanity.io is a great headless cms to create and manage your content and feed it to different places in a convenient way.
Groq is a declarative language to query your data kept by sanity. Here are some notes regarding the subject.
For example you have following simple schema with two objects "Post" and "Tag". And post may have relations to 0 or more tags. Here is a schemas for those objects.
copied javascript
// schema for Post
{
name: 'post',
title: 'Post',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'tags',
title: 'Tags',
type: 'array',
of: [{type: 'reference', to: {type: 'tag'}}],
}
}
}
copied javascript
// schema for Tag
{
name: 'tag',
title: 'Tag',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
{
name: 'slug',
title: 'Slug',
type: 'slug',
options: {
source: 'title',
maxLength: 96,
},
},
],
}
In this case to query all posts which have relation to tag with slug `tag-example` we have to do the following:
copied groq
*[_type == "post" && "tag-example" in tags[]->slug.current]{
title
}
If we want to make `tag-example` dynamic we can put there `$slug` placeholder and feed needed value in an object as second parameter to fetch function:
copied javascript
const query = groq`
*[_type == "post" && $slug in tags[]->slug.current]{
title
}
`;
sanity.fetch(yourQuery, { slug })