How to Write a GROQ Join Query for a Reference Type

1 replies
Last updated: Jul 21, 2021
NOTE: I already answered my own question, thanks
-------
Hi everyone, just started using Sanity a few days ago and am having trouble writing a join query for my reference type. End goal is to create a testimonials slider on my homepage.

Schema.js:

export default {
  name: 'homepage',
  type: 'document',
  title: 'Homepage Data',
  fields: [
    ...
    {
      name: 'home_testimonials',
      type: 'array',
      of: [{ type: 'reference', to: [{ type: 'testimonial' }] }],
      title: 'Homepage Testimonials',
    },
  ],
}; 
Custom doc:

// testimonial.js
export default {
  name: 'testimonial',
  title: 'Testimonial',
  type: 'document',
  fields: [
    {
      name: 'author',
      type: 'string',
      title: 'Author',
    },
    {
      name: 'jobTitle',
      type: 'string',
      title: 'Job Title',
    },
    {
      name: 'content',
      type: 'string',
      title: 'Content',
    },
  ],
};
Based on this doc (
https://www.sanity.io/docs/reference-type ) I wrote this GROQ query:
export const homepageQuery = `*[_type == "homepage"] {
  ...,
  "home_testimonials": testimonial[]{
    testimonial->{content, jobTitle, author}
  }
}`;
It is returning the correct number of results, but they each look like this:

home_testimonials: [{
  "_key":"4185e4bd9cea",
  "_ref":"07c6f4c5-f09b-456b-9d1b-95af390f389b",
  "_type":"reference"
  },
  ...
] 
I'm expecting to see
home_testimonials
filled with all my custom fields (
jobTitle
,
author
, etc...) instead of just the reference ID.
Pretty sure I'm approaching this all wrong so any pointers are appreciated.
🙏
AI Update

Glad you figured it out! For anyone else who comes across this thread with a similar issue, the solution is to fix the GROQ query syntax. The correct query should be:

*[_type == "homepage"] {
  ...,
  "home_testimonials": home_testimonials[]->{
    content, 
    jobTitle, 
    author
  }
}

The key differences:

  • Use home_testimonials[]-> (the actual field name from your schema, not "testimonial")
  • The -> operator dereferences the reference to get the actual testimonial document
  • No need for a nested testimonial-> inside

This will expand each reference in the home_testimonials array and return the actual content, jobTitle, and author fields from each referenced testimonial document.

You can learn more about dereferencing in GROQ in the reference type documentation and the GROQ query cheat sheet.

Ok, never mind friends. After some playing around, I got it working like this:
*[ _type == "homepage" ]{ ..., home_testimonials[]->{content, jobTitle, author} }

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.

Was this answer helpful?