GROQ: Query reverse relationships - get all businesses by county reference
Perfect! You're looking for a "reverse reference" query, and GROQ has exactly what you need with the references() function.
Instead of adding businesses to a county (which would be awkward data entry), you can keep your current approach where you add the county reference to each business document during data entry. Then use references() to query all businesses in a specific county.
Here's how it works:
Your Business schema (what you probably already have):
{
name: 'business',
type: 'document',
fields: [
{name: 'name', type: 'string'},
{name: 'address', type: 'string'},
{
name: 'county',
type: 'reference',
to: [{type: 'county'}]
}
]
}Query all businesses in a specific county:
*[_type == "business" && references("county-document-id")]Or if you want to query from the county document itself:
*[_type == "county" && slug.current == "your-county-slug"][0]{
name,
"businesses": *[_type == "business" && references(^._id)]{
name,
address
}
}The ^._id syntax accesses the parent county's ID from within the subquery, so it automatically finds all businesses that reference that specific county.
This is exactly the pattern described in the references() function documentation - it lets you do reverse lookups without having to maintain relationships in both directions. Your users just add the county when creating a business (which makes sense from a data entry perspective), and you can still easily query all businesses by county.
Show original thread2 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.