sanitygroq

GROQ: Query one-to-many relationship with parameter as query input


I have a blog built in NextJS, backed by Sanity. I want to start tagging posts with tags/categories.

Each post may have many categories.

Category is a reference on post:

 defineField({
   name: 'category',
   title: 'Category',
   type: 'array',
   of: [
     {
       type: 'reference',
       to: [
         {
           type: 'category',
         },
       ],
     },
   ],
 }),

This is my GROQ query:

*[_type == "post" && count((category[]->slug.current)[@ in ['dogs']]) > 0] {
  _id,
  title,
  date,
  excerpt,
  coverImage,
  "slug": slug.current,
  "author": author->{name, picture},
  "categories": category[]-> {name, slug}
}

The above works, when it is hardcoded, but swapping out 'dogs' with $slug for example will cause the query to fail. (Where $slug is a param provided)

*[_type == "post" && count((category[]->slug.current)[@ in [$slug]]) > 0] 
{
  $slug: 'travel' 
}

How do I make the above dynamic?


Solution

  • I can't believe it. Rookie mistake. I needed to pay more attention in the Sanity IDE. (To be fair there was a UI bug that hid the actual issue)

    The param should not contain the $. E.g the following works in the GROQ IDE.

    {
      slug: 'travel' 
    }