Understanding Groq queries in Sanity.io Slack thread
14 replies
Last updated: Feb 26, 2021
E
hey guys! i have a groq question... is this possible? `
*[_type == 'collection' && *[items && slug.current == 'look-1']]
itemsis an array of objects under a
collection.. i want to get the collection that has that
itemof a particular slug π
Feb 25, 2021, 5:57 PM
D
*[_type == 'collection' && 'look-1' in items[].slug.current]
slugis a property of each
itemin
items
Feb 25, 2021, 6:18 PM
D
That query is essentially doing an array map on
itemsto make an array of all the slugs, and then checking if any of them match 'look-1'
Feb 25, 2021, 6:19 PM
E
will the
in getStaticPaths for /[collection]/[item]
^operator also work? context:
[...*[_type == 'collection'].items] { 'collectionSlug': ^.slug.current, 'itemSlug': slug.current, },
Feb 25, 2021, 6:20 PM
E
nope π€ i need to read up more on this π
Feb 25, 2021, 6:22 PM
E
...
[...*[_type == 'collection'].items]doesnt work... how do i flatten all items of all collections ?
Feb 25, 2021, 6:38 PM
E
i guess this is kind of what im trying to do... not yet possible still? https://stackoverflow.com/questions/58433891/filter-query-result-by-field-value-inside-array-of-objects-sanity-io-groq
Feb 25, 2021, 7:21 PM
D
If you want to get all collections which have a property
itemswhich contains a slug, then I'm pretty sure I was on the right track. It sounds like you want to do something different though?
Feb 25, 2021, 8:36 PM
D
If you are trying to bring back a particular
Would that not work for you? I'm not 100% sure what you are trying to do, so I'm kind of taking a shot and seeing if I get it right here
π
itemin the
itemsarray within your
collectionresults, based on a slug you provide, then you could actually do that within the projection:
*[_type == 'collection']{ ..., "targetItem": items[slug.current == $slug] }
π
Feb 25, 2021, 8:40 PM
E
omg!
Feb 25, 2021, 8:42 PM
E
i think that's it! didn't know the syntax
items[conditional here]!
Feb 25, 2021, 8:43 PM
E
will give it a go, thank you djeglin
Feb 25, 2021, 8:43 PM
D
Yeah... So, because projections are just groq statements in and of themselves, you can use the filter (like you do to start your query) inside it. You're replacing the
*(which is the array to filter) with
itemshere, so the filter operates against that child array of the item being projected. I'm using it in a couple of places in the project I'm working on at the moment
Feb 25, 2021, 8:45 PM
E
thank you so much
user M
! very greatful for spending the time to explain it to me too π i learned something new!Feb 26, 2021, 8:02 AM
D
No problem! I ask questions all the time... The least I can do is try to help others where I can in return π
Feb 26, 2021, 12:09 PM
Sanityβ build remarkable experiences at scale
The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.