Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

Hi, anyone able to help with a relationship thing? I have several schemas set up, like, Country, County, and Business, each country has counties (county) each county has...

2 replies
Last updated: Dec 29, 2020

Hi, anyone able to help with a relationship thing?
I have several schemas set up, like, Country, County, and Business, each country has counties (county) each county has businesses, so, each business belongs to one county and I want to be able to GROQ all businesses in a county.

I have made a query for all counties in a country where I add a county to a country then I can get the county names from the country *`*[_type == "country"]{...,county[]->}`* but I don't want the user to have to add the business to a county as logically when you're entering the address details for a business in the CMS you'd do it all in on data entry form, I guess... If it's not all in one place then the user will probably forget to add the business to the county then there'll be no record of it when searching for businesses by county.

What I trying to articulate (badly) is that I want to do the reverse for relationships so I can get all businesses in a county by adding the county to the business rather than the business to the county

Dec 28, 2020, 8:11 PM

You should be able to do that with something like this:

*[type == "county"]{
  ...,
  "businesses": *[_type=="business" && references(^._id)]{
    ...
  }
}

Dec 28, 2020, 8:41 PM

Brilliant, thanks

user J
🙏

Dec 29, 2020, 5:44 AM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.