Querying for subcategories of articles written by a specific author in a nice way.

5 replies
Last updated: Jun 11, 2023
Is there a nice way to get the subcategory of all the articles a particular author has written? I did something like
export const conferencesAuthorHasWrittenFor = groq`
  *[_type == 'author' && slug.current == $slug && archived == false][0]{
    "conferencesWrittenFor": *[_type == 'post' && references(^._id)] | order(publishedAt desc, _updatedAt desc){
      "subcategory": subcategory->{title, 'slug': slug.current, "parentSlug": parent->slug.current, "parentTitle": parent->title}
    },
  }
`
but that gives me an array of objects that have
subcategory: [Object]
or
subcategory: null
in them. Ideally I would like to have it return an array of strings like
/news/${parentCategory}/${subCategory}
oh and I want to make them unique
Jun 9, 2023, 10:13 PM
I would probably do something like:
*[_type == 'author' && slug.current == $slug && archived == false][0] {
  "subcategories": array::unique(*[_id in *[_type == "post" && references(^.^._id)].subcategory._ref)[] {
    path: "/news/" + parent->.slug.current + "/" + slug.current
  }.path
}

Jun 10, 2023, 10:02 AM
πŸ€”
export const conferencesAuthorHasWrittenFor = groq`
*[_type == 'author' && slug.current == $slug && archived == false][0] {
  "subcategories": array::unique(*[_id in *[_type == "post" && references(^.^._id)]].subcategory._ref)[] {
    "path": "/news/" + parent->.slug.current + "/" + slug.current
  }.path
}
`
is currently returning
{ subcategories: [] }
when I know for sure there should be some returned πŸ€”
Jun 10, 2023, 10:31 PM
*[_type == 'author' && slug.current == $slug && archived == false][0] {
  "subcategories": array::unique(*[_id in *[_type == "post" && references(^.^._id)].subcategory._ref])[] {
    "path": "/news/" + parent->.slug.current + "/" + slug.current
  }.path
}
Had to add a
]
at the end of
subcategory._ref
and then surround
path
in quotes. But it works! Thank you!
Jun 10, 2023, 10:35 PM
I also switched this over to using
_id == $authorId
like you suggested in the other thread as well
Jun 10, 2023, 11:06 PM
Great!
Jun 11, 2023, 11:35 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?