GROQ query to resolve references and keep the _key property in an array

8 replies
Last updated: Mar 1, 2021
Hi guys, I have a simple array of references within a document. Does anyone know the GROQ query I need to write to resolve references AND keep the _key property for each element in the array?

This query: *[_id == $id]{items}

Gives me this result:
[
  {
    "items": [
      {
        "_key": "1acc50cf5ffc",
        "_ref": "f4cae0ea-16a0-446b-a835-a93b001dd1eb",
        "_type": "reference"
      },
      {
        "_key": "be9bad61ab5e",
        "_ref": "098b7fce-f26c-4643-90c1-8ef6b8f61bbf",
        "_type": "reference"
      }
    ]
  }
]
Adding
[]->
to items resolves each item reference, but it also strips out the
_key
property. Is there a way to include it while still resolving the reference all with a single GROQ query?
Mar 1, 2021, 4:01 PM
Out of interest... why do you need to keep the
_key
property? Just curious
Mar 1, 2021, 4:04 PM
I need to create relative references to the documents inside this document. I have a separate array of objects where each object has a relative reference to an item in the array. At the same time I also need to resolve the item in order to determine it's type. The
items
array can contain references to many different types and I'm using a custom InputComponent to filter out references based on the values in other fields.
Mar 1, 2021, 4:06 PM
Hi User. One way would be to call for the dereferenced data as well as the key. Something like:

*[_id == $id]{
  'items': items[]->,
  'itemKey': items[]._key
}

Mar 1, 2021, 4:08 PM
Or you could do this:
*[_id == $id]{
  items[]{
    ...,
    "doc": *[_id == ^._ref][0]
  }
}
Mar 1, 2021, 4:14 PM
So you're adding a new property,
doc
to each of the items in the
items
array which fetches the referenced document
Mar 1, 2021, 4:16 PM
Nice. Thanks for the answers
user A
and
user M
. Both solutions seem to work fine. Though I think I prefer
user M
s solution as it groups the document with the item. Thank you both!
Mar 1, 2021, 4:20 PM
Another variation, which is slightly faster:

*[_id == $id]{
  items[]{
    _key,
    ...(@->)
  }
}
"Take _key from the array item, then splat all the properties of following this reference"
Mar 1, 2021, 4:59 PM
Oh, that is lovely
user Z
🤩
Mar 1, 2021, 9:45 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?