Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

I'm still trying to work out how to write a subquery that pulls in references that are based on the parent query. My original thought process is here: <https://sanity-io-land.slack.com/archi...

4 replies
Last updated: Jan 5, 2021

I'm still trying to work out how to write a subquery that pulls in references that are based on the parent query. My original thought process is here: https://sanity-io-land.slack.com/archives/C9Z7RC3V1/p1608667211425800
Ultimately, I'm hoping to query all staff and within that query, query for all posts that reference that staff in an array called

involved
. The closest I got was the following, but unfortunately it pulls in too much (it gets all the posts where that staff member is included in
involved
, but it also includes posts where that staff member has been referenced using internal links):

*[_type == "staff"] | order(firstName asc, lastName asc) {
  firstName,
  lastName,
  slug,
  'postCount': count(*[_type == "posts" &amp;&amp; references(^._id)])
}

Jan 5, 2021, 6:38 PM

Hi Geoff! There seems to be an issue with array traversal that we're investigating. It occurs when using a

string in array[]-&gt;string
pattern, so when dereferencing is involved. This would explain the lack of results you were seeing with that approach in the original thread.
Could you try something like this?

*[_type == "staff"] | order(firstName asc, lastName asc) {
  firstName,
  lastName,
  slug,
  'postCount': count(*[_type == "posts" &amp;&amp; ^._id in involved[]._ref])
}

Jan 5, 2021, 7:29 PM

Yes! That works perfectly! Thank you, Peter!

Jan 5, 2021, 9:10 PM

Glad to hear!

Jan 5, 2021, 10:36 PM

Awesome! πŸš€

Jan 5, 2021, 10:39 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.