πŸ‘€ See Sanity in action: Watch product demo now β†’

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 – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in