Querying reverse relationships in Sanity with GROQ
3 replies
Last updated: Aug 29, 2021
S
has anyone got an example of a reverse relationship? For example, I have "work" and "work categories" as 2 separate documents. On "work" i reference "work category" - I want to loop over the work categories and show the related work items from each, is there a way I can do this with Sanity? (I'm using NextJs for the FE)
Aug 29, 2021, 2:50 PM
Sure! I don’t have your exact schemas, but to get a gist of it:• Assuming that your
workdocument has an array of references to
workCategorycalled
workCategories• Here using a sub-query where I match the parent
_id, that is, the
_idof the
workCategorydocument, to an
_refinside of the references field in the
workdocument
*[_type == "workCategory"]{ _id, name, // using the parent operator ^ "relatedWork": *[^._id in workCategories[]._ref]{ _id, name, // other fields } }
Aug 29, 2021, 3:58 PM
D
This is a slightly different query than what you requested, where ‘related’ is an array of unique work that has at least 1 of the parent work document’s categories
https://groq.dev/7XeyO5v20NxEhj2aUjHBY4
I also add an example with User’s query:
https://groq.dev/7XeyO5v20NxEhj2aUjHZBY
*[_id == "work-2"][0] { ..., "related": *[ _type == "work" && _id != "work-2" && count(cats[@._ref in ^.^.cats[]._ref]) > 0 ] { _id, } }
https://groq.dev/7XeyO5v20NxEhj2aUjHBY4
I also add an example with User’s query:
*[_id == "work-2"][0] { ..., "related": *[_type == "cat" && _id in ^.cats[]._ref] { _id, "workDocs": *[_type == "work" && _id != "work-2" && references(^._id)] { _id} } }
https://groq.dev/7XeyO5v20NxEhj2aUjHZBY
Aug 29, 2021, 4:27 PM
D
This is a slightly different query than what you requested, where ‘related’ is an array of unique work that has at least 1 of the parent work document’s category
https://groq.dev/7XeyO5v20NxEhj2aUjHBY4
I also add an example with User’s query:
https://groq.dev/7XeyO5v20NxEhj2aUjHZBY
*[_id == "work-2"][0] { ..., "related": *[ _type == "work" && _id != "work-2" && count(cats[@._ref in ^.^.cats[]._ref]) > 0 ] { _id, } }
https://groq.dev/7XeyO5v20NxEhj2aUjHBY4
I also add an example with User’s query:
*[_id == "work-2"][0] { ..., "related": *[_type == "cat" && _id in ^.cats[]._ref] { _id, "workDocs": *[_type == "work" && _id != "work-2" && references(^._id)] { _id} } }
https://groq.dev/7XeyO5v20NxEhj2aUjHZBY
Aug 29, 2021, 4:27 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.