How to Reference an Enclosing Document of a Reference in GROQ
7 replies
Last updated: May 26, 2022
K
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:
Here's my sample data:
And here's my gorq query issue:
Is this even possible?
{ 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' }] }, ] }
- Dad1 - Kid1 - friend -> Kid2 - Dad2 - Kid2
*[_type=="kid"]{ name, "parentName": ^.name, "friendsName": friend->name, "friendsDadsName": friend.^.name <- NOT WORKING }
May 25, 2022, 4:00 PM
R
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
K
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
K
so something like:
but that does not work either
"friendsDadsName": *[_type=='dad' && kids[]._id == friend._id]
May 25, 2022, 9:59 PM
K
thoughts?
May 25, 2022, 10:45 PM
G
Could you try this and see what you get?
This would return a subquery for a
'friendsDadsName': *[_type == 'dad' && ^.friend._ref in kids[]._ref][0].name
dadwhose `kid`’s `friend`’s
_refmatches the
_refin the
kidsarray. It then returns the name (i.e., the `dad`’s name) of the first value.
May 26, 2022, 3:29 PM
K
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
G
Great! You’re welcome!
May 26, 2022, 7:13 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.