Sanity GROQ: order results by the value of a referenced field

1.5k Views Asked by At

I have the document type celeb. And the document type fact. Each fact references a celeb. I want to list celebs ordered by their most recently updated facts. So the celeb which has just had a fact added about them would show up at the top.

How can I do that?

1

There are 1 best solutions below

0
On

Answer from Alexander Staubo in the Sanity help channel on Slack

Something like:

*[_type == "celeb"] {
 _id,
 name,
 "latestFact": *[_type == "fact" && celeb._ref == ^._id] | order(_updatedAt desc)[0]
}
 | order(latestFact._updatedAt desc)

This assumes that each fact has a field called celeb which is a ref to the celeb document.

For each celeb, it finds the latest fact. At the end, it sorts all the celebs by the date.