Unlock seamless workflows and faster delivery with our latest releases – get the details

GROQ Query - How to Filter Posts by Category if it's an Array

6 replies
Last updated: Jun 29, 2021
For GROQ queries how do you filter posts by category if its an array
export default {
  name: 'post',
  title: 'Post',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string',
    },
    {
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96,
      },
    },
    {
      name: 'author',
      title: 'Author',
      type: 'reference',
      to: {type: 'author'},
    },
    {
      name: 'mainImage',
      title: 'Main image',
      type: 'image',
      options: {
        hotspot: true,
      },
    },
    {
      name: 'categories',
      title: 'Categories',
      type: 'array',
      of: [{type: 'reference', to: {type: 'category'}}],
    },
    {
      name: 'publishedAt',
      title: 'Published at',
      type: 'datetime',
    },
    {
      name: 'body',
      title: 'Body',
      type: 'blockContent',
    },
  ],

  preview: {
    select: {
      title: 'title',
      author: 'author.name',
      media: 'mainImage',
    },
    prepare(selection) {
      const {author} = selection
      return Object.assign({}, selection, {
        subtitle: author && `by ${author}`,
      })
    },
  },
}
Jun 29, 2021, 7:39 PM
so when I do it like this it doesn't work
*[_type == "post" && 'Paintings' in categories[]->name] {
        title,
        slug,
        mainImage{
          asset->{
          _id,
          url
        }
      },
			categories
}
Jun 29, 2021, 7:48 PM
This is what the category data looks like when I just query all posts
{
  "categories": [
    {
      "_key": "1d8df8bf7a3a",
      "_ref": "49a70477-bf23-4d65-a0da-e84608fb7a40",
      "_type": "reference"
    }
  ],
  "mainImage": {
    "asset": {
      "_id": "image-37ac1ca3329a254d9de6b2b3a85b8e45444ac4b8-2712x3511-jpg",
      "url": "<https://cdn.sanity.io/images/7hxv42mc/production/37ac1ca3329a254d9de6b2b3a85b8e45444ac4b8-2712x3511.jpg>"
    }
  },
  "slug": {
    "_type": "slug",
    "current": "donnie-s-gullah-fruit-cart"
  },
  "title": "Donnie's Gullah Fruit Cart"
}
Jun 29, 2021, 7:48 PM
what is an example of
*[_type == "post"] {
  categories[]->
}
in your dataset?
Jun 29, 2021, 7:50 PM
what is an example of
*[_type == "post"] {categories[]->
}
Jun 29, 2021, 7:50 PM
Ahh so its title and not name! I was able to successfully query by category now. Thank you so much I was getting so frustrated &gt;_&lt;
Jun 29, 2021, 7:55 PM
Awesome!
Jun 29, 2021, 7:58 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?