Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Combining queries in Sanity.io: how to grab data from two different documents with one query

11 replies
Last updated: Mar 7, 2022
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
// 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
  }
}
However, when I do this I get
null
I'll put my actual queries in the comments.Thanks,
Mar 7, 2022, 11:20 PM
So, to get the data individually I can do

*[_type == "collections" && publish == true] {
    heading,
    heroImage,
    slug,
    featured,
  }
and

*[_type == "marketing_pages" && slug.current == "collections"]{
   seo_title,
   seo_desc,
   page_builder,
   
 }
which both work on their own
Mar 7, 2022, 11:22 PM
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
ahhhh
Mar 7, 2022, 11:27 PM
Thanks so much!!!
Mar 7, 2022, 11:27 PM
No problem
Mar 7, 2022, 11:27 PM
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
ahhhh
Mar 7, 2022, 11:27 PM
Thanks so much!!!
Mar 7, 2022, 11:27 PM
No problem
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.

Was this answer helpful?