🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Querying for articles associated with tags in a list component in one query.

5 replies
Last updated: Oct 24, 2022
Hi Sanity Team! I need some help with a GROQ query…Let’s say I have a list component that displays articles and has an array of tags to switch between articles that are associated with that tag.

Would it be possible to get all the articles that are associated with each tag, in one query?

Something like:
*[_type == “list_component” && _id=“dsf”] {tags} {
//“tagName”: *[_type == “article” && references(tagId)]
}

I’d like to end with a result that looks something like this:
{
Tag1: [Array of articles associated with this tag],
Tag2: [Array of articles associated with this tag],

TagN: [Array of articles associated with this tag]
}

Currently, I have one query to get the tags from my list component. Then I have another query that gets the articles that reference each tag, but I would like to have it all in one query.

Thanks in advance! and sorry if my question isn’t very clear
😅
Oct 21, 2022, 5:57 PM
GROQ seems to need the leftmost (or solo) "keys" to be either string literals representing a value, or existing fields/docs.
Someone asked last night about grouping by date and I was going to use string::startsWith and string::split to peel off the year at the front of the date in an experiment, but you can't have pure text and try to "project" off it, like little 'for' loops.

I'd love it if you could, but I get why you can't.

Something like

["2022", "2021"] {

"postsFromThisYear" : *[_type=="post" && year==^]

}

You might try moving this particular question to the
groq channel as there are some clever folks, including at least one of the GROQ devs himself, who might be able to cook something up.
Oct 21, 2022, 6:07 PM
I was afraid that might be the case… But yeah I’ll ask this again in groq and see if I can get any luck there. Thanks!
Oct 21, 2022, 6:14 PM
You should be able to do something like this:
*[_type == "list_component" && _id="dsf"].tags[]{
  tagName, //or whatever field contains the name of the tag
  "relatedArticles": *[_type == "article" && references(^._id)]
}
Oct 24, 2022, 5:45 PM
This is exactly what I wanted, thank you!
Oct 24, 2022, 5:59 PM
You're welcome!
Oct 24, 2022, 7:52 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?