Combining queries in Sanity.io: how to grab data from two different documents with one query
11 replies
Last updated: Mar 7, 2022
D
Hey all, I'm trying to grab data from two different documents with one query. From my understanding of the documentation this should be possible by doing something like
However, when I do this I get
// Specify sets of projections for different content types in an array content[]{ _type == 'type1' => { // Your selection of fields for type1 }, _type == 'type2' => { // Your selection of fields for type2 "url": file.asset->url // Use joins to get data of referenced document } }
nullI'll put my actual queries in the comments.Thanks,
Mar 7, 2022, 11:20 PM
D
So, to get the data individually I can do
and
which both work on their own
*[_type == "collections" && publish == true] { heading, heroImage, slug, featured, }
*[_type == "marketing_pages" && slug.current == "collections"]{ seo_title, seo_desc, page_builder, }
Mar 7, 2022, 11:22 PM
D
but something like this doesn't work
content[]{ _type == "collections" && publish == true] => { heading, heroImage, slug, featured, }, _type == "marketing_pages" && slug.current == "collections" => { seo_title, seo_desc, page_builder, }, }
Mar 7, 2022, 11:26 PM
The example you have above is for conditionally rendering fields within a document. To combine queries you can do it like this:
{ "first": *[_type == "collections" && publish == true] { heading, heroImage, slug, featured }, "second": *[_type == "marketing_pages" && slug.current == "collections"] { seo_title, seo_desc, page_builder } }
Mar 7, 2022, 11:26 PM
D
ahhhh
Mar 7, 2022, 11:27 PM
D
Thanks so much!!!
Mar 7, 2022, 11:27 PM
D
but something like this doesn't work
content[]{ _type == "collections" && publish == true] => { heading, heroImage, slug, featured, }, _type == "marketing_pages" && slug.current == "collections" => { seo_title, seo_desc, page_builder, }, }
Mar 7, 2022, 11:26 PM
The example you have above is for conditionally rendering fields within a document. To combine queries you can do it like this:
{ "first": *[_type == "collections" && publish == true] { heading, heroImage, slug, featured }, "second": *[_type == "marketing_pages" && slug.current == "collections"] { seo_title, seo_desc, page_builder } }
Mar 7, 2022, 11:26 PM
D
ahhhh
Mar 7, 2022, 11:27 PM
D
Thanks so much!!!
Mar 7, 2022, 11:27 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.