Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Querying reverse relationships in Sanity with GROQ

3 replies
Last updated: Aug 29, 2021
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
work
document has an array of references to
workCategory
called
workCategories
• Here using a sub-query where I match the parent
_id
, that is, the
_id
of the
workCategory
document, to an
_ref
inside of the references field in the
work
document
*[_type == "workCategory"]{
  _id,
  name,
  // using the parent operator ^ 
  "relatedWork": *[^._id in workCategories[]._ref]{
    _id,
    name,
    // other fields
  }
}
Aug 29, 2021, 3:58 PM
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

*[_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
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

*[_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.

Was this answer helpful?