Querying for specific categories and subcategories in Sanity.io

12 replies
Last updated: Jan 17, 2023
Hey guys! I need to get all posts related to a specific category and its subcategoriesI do not understand how to do this in one request, now it only works if I hardcode the value of the subcategory in
references(…)
Jan 16, 2023, 3:32 PM
*[_type == "blogPostTag" && key.current == "digital-marketing"][0]{
  "posts": *[_type == "localizedBlogPostEntry" && references(^._id, "427f4454-22f7-40a0-8d88-db31fb20ad7b")],
  "subCategories": *[_type == "blogPostTag" && references(^._id)]._id
}
Jan 16, 2023, 3:33 PM
Another way but still with hardcoded value…
Jan 16, 2023, 3:53 PM
It's a little difficult without seeing how you have your schema structured. Check the groq cheatsheet to see if it helps or post your schema and I can take a look.
https://www.sanity.io/docs/query-cheat-sheet
Jan 16, 2023, 4:01 PM
BlogPostTag (category and sub-category)
export default {
  name: 'blogPostTag',
  title: 'Blog tag',
  type: 'document',
  preview: {
    select: {
      title: 'title',
      key: 'key',
      isParent: 'isParent',
      parentCategory: 'parentCategory.title'
    },
    prepare({ title, key, isParent, parentCategory }) {
      return {
        title: title,
        subtitle: `${
          isParent
            ? `/blog/tag/${key.current}`
            : parentCategory
              ? `Sub-category of ${parentCategory}`
              : `The parent category is not set!`
        }`,
        media: isParent ? ParentCategoryIcon : AiOutlineTag
      };
    }
  },
  fieldsets: [
    {
      title: 'SEO & metadata',
      name: 'metadata',
      options: { collapsible: true, collapsed: true }
    }
  ],
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string'
    },
    { ...keyFieldOptions },
    {
      name: 'description',
      title: 'description',
      type: 'text'
    },
    {
      title: 'Cover Image',
      name: 'coverImage',
      type: 'image'
    },
    {
      title: 'Icon Image',
      name: 'iconImage',
      type: 'image'
    },
    {
      title: 'Parent category?',
      name: 'isParent',
      type: 'boolean'
    },
    {
      title: 'Link to parent category',
      name: 'parentCategory',
      type: 'reference',
      to: [{ type: 'blogPostTag' }],
      hidden: ({ parent }) => !!parent.isParent
    },
    {
      title: 'Meta title',
      name: 'metaTitle',
      type: 'string',
      description: 'This title populates meta-tags on the webpage',
      fieldset: 'metadata'
    },
    {
      title: 'Meta description',
      name: 'metaDescription',
      type: 'text',
      description: 'This description populates meta-tags on the webpage',
      fieldset: 'metadata'
    },
    {
      title: 'Open Graph Image',
      name: 'openGraphImage',
      type: 'image',
      description: 'Image for sharing previews on Facebook, Twitter etc.',
      fieldset: 'metadata'
    }
  ]
};
Jan 16, 2023, 4:02 PM
Blog post schema
export default {
  name: 'localizedBlogPostEntry',
  title: 'Blog Post',
  type: 'document',
  preview: createPreview(),
  fieldsets: [
    {
      title: 'Blog taxonomy',
      name: 'taxonomy'
    },
    {
      title: 'SEO & Social media',
      name: 'metadata',
      options: { collapsible: true, collapsed: true }
    }
  ],
  fields: [
    {
      title: 'Title',
      name: 'textTitle',
      type: 'string'
    },
    {
      ...keyFieldOptions
    },
    {
      title: 'Content (New)',
      name: 'rte',
      ...richTextEditor
    },
    {
      title: 'Release date',
      name: 'releaseDate',
      type: 'datetime',
      validation: (Rule) => Rule.required()
    },
    {
      title: 'Author',
      name: 'author',
      type: 'reference',
      to: { type: 'blogPostAuthor' },
      validation: (Rule) => Rule.required()
    },
    {
      title: 'Category',
      name: 'tags',
      type: 'array',
      of: [{ type: 'reference', to: { type: 'blogPostTag' } }],
      validation: (Rule) => Rule.required().min(1),
      fieldset: 'taxonomy'
    }
  ]
};
Jan 16, 2023, 4:04 PM
*[_type == localizedBlogPostEntry]{
  "categories": tags[] ->

I'm not sure why you used different names than the titles. This makes it very confusing because I'm not sure what you are calling categories and what you are calling subcategories. The query is called on the
name
of the document.
Jan 16, 2023, 4:11 PM
I think that will work for what you want though.
Jan 16, 2023, 4:12 PM
It is legacy names. Category and sub-category are same document type - blogPostTag
Jan 16, 2023, 4:13 PM
No, your query will return all the posts
Jan 16, 2023, 4:15 PM
I need to fetch specific category with all posts related to that specific category and its subcategories
Jan 16, 2023, 4:17 PM
*[_type == category && categoryName == "name"] {
"subcategory": subcategoryName -> {
"posts": postName[ ] -> }}
Jan 16, 2023, 4:39 PM
Thanks! I will check if it works for me
Jan 17, 2023, 8:20 AM

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?