Querying arrays of objects and relationships in Groq
17 replies
Last updated: Apr 10, 2023
S
Hey everyone!Could anyone guide me on how I could do a groq query for an array of objects?
I want images to return an array of images with just their url…
I want images to return an array of images with just their url…
groq`*[_type == "art"]{ _createdAt, _id, "category": category.title, "slug": slug.current, "featureImage": featureImage.asset->url, images }`
Apr 7, 2023, 9:37 PM
P
you probably need to use a join https://www.sanity.io/docs/query-cheat-sheet#e82ab8c0925b
Apr 7, 2023, 10:17 PM
You need to iterate over the array
[], dereference the asset
->, then access the url:
'images': images[].asset->url
Apr 10, 2023, 8:09 PM
S
Thanks for that!
Apr 10, 2023, 8:10 PM
S
I should have noted I solved that with this just for reference in the future:
'images': images[] { alt, "url": image.asset->url }
Apr 10, 2023, 8:11 PM
S
In a similar issue, I am having trouble figuring out how to query a relationship
Apr 10, 2023, 8:11 PM
S
I have an array of a document type, artSeries. But I can’t figure out how to grab the information I need for the artSeries
So far I have tried doing something like the following:
{ _createdAt: '2023-04-10T19:34:13Z', _id: 'homepageImages', _rev: 'QNM76uqvKuoc4uTWDKb5RR', _type: 'homepageImages', _updatedAt: '2023-04-10T19:35:32Z', artSeries: [ [Object] ], title: 'Homepage Images' }
groq`*[_type == "homepageImages" ]{ _id, _createdAt, "artSeries": artSeries[] { not sure what I might do here haha }, }`
Apr 10, 2023, 8:13 PM
S
I need to get an array of artSeries documents that is referenced in the homepageImages
Apr 10, 2023, 8:23 PM
S
Right now the only info I get about each artSeries is this:
{"_key":"33077cdafee1","_ref":"4bd3b6a8-b353-4f14-9975-f3a847055509","_type":"reference"}
Apr 10, 2023, 8:24 PM
S
I just can’t figure out how to use the _ref to make another query for the artSeries with the same _id associated to it
Apr 10, 2023, 8:24 PM
Ah, you don’t need to use a named field in this case. Something like this should work:
*[_type == "homepageImages" ]{ _id, _createdAt, artSeries[]->{ //add projection here or remove the brackets if you want all of the fields. }, }
Apr 10, 2023, 8:51 PM
S
Oh great! That was much easier than I was making it
Apr 10, 2023, 8:54 PM
S
And sorry just one other thing. Is there a way to order the artSeries by _createdAt?
Apr 10, 2023, 9:01 PM
Yeah try:
*[_type == "homepageImages" ]{ _id, _createdAt, artSeries[]-> | order(_createdAt asc) }
Apr 10, 2023, 9:12 PM
S
Thank you!
Apr 10, 2023, 9:12 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.