How to Reference an Enclosing Document of a Reference in GROQ

7 replies
Last updated: May 26, 2022
Hello Sanity Experts ! I have this issue trying to figured out how to reference an enclosing document of a reference in groq. I have the following schema:

{
    name: 'dad',
    title: 'Daddy',
    type: 'document',
    fields: [
      {
        name: 'name',
        title: "Daddy's Name",
        type: 'string',
      },
      {
        name: 'kids',
        title: 'Kids',
        type: 'array',
        of: [
          {
            type: 'reference',
            to: [{ type: 'kid' }],
          },
        ],
      }
    ]
}
{
    name: 'kid',
    title: 'Kid',
    type: 'document',
    fields: [
      {
        name: 'name',
        title: "Kid's Name",
        type: 'string',
      },
      {
        title: 'Friend',
        name: 'friend',
        type: 'reference',
        to: [{ type: 'kid' }]
      },
    ]
}
Here's my sample data:

- Dad1
  - Kid1
    - friend -> Kid2

- Dad2
  - Kid2
And here's my gorq query issue:

*[_type=="kid"]{
  name,
  "parentName": ^.name,
  "friendsName": friend->name,
  "friendsDadsName": friend.^.name  <- NOT WORKING
}
Is this even possible?
May 25, 2022, 4:00 PM
I think you want to use a nested projection here.
*[_type=="kid"]{
  name,
  "parentName": ^.name,
  "friendsName": friend->name,
  "friendsDadsName": *[_type == 'dad' && references(^.friend)]
}
May 25, 2022, 6:01 PM
hi
user M
, thanks for you response, but this does not seem to work. Friends's dad's one of the kids needs to match the friend.
May 25, 2022, 9:52 PM
so something like:
"friendsDadsName": *[_type=='dad' && kids[]._id == friend._id]
but that does not work either
May 25, 2022, 9:59 PM
thoughts?
May 25, 2022, 10:45 PM
Could you try this and see what you get?

'friendsDadsName': *[_type == 'dad' && ^.friend._ref in kids[]._ref][0].name
This would return a subquery for a
dad
whose `kid`’s `friend`’s
_ref
matches the
_ref
in the
kids
array. It then returns the name (i.e., the `dad`’s name) of the first value.
May 26, 2022, 3:29 PM
hi
user A
, thanks so much, it worked!... What I was confused the most about was the scope when using
^.
. I could not figure out if the scope boundaries were also square brackets or just curly braces. Now it makes more sense. Thanks again.
May 26, 2022, 5:43 PM
Great! You’re welcome!
May 26, 2022, 7:13 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?