✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

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.
🙏
Jul 21, 2021, 6:28 AM
Ok, never mind friends. After some playing around, I got it working like this:
*[ _type == "homepage" ]{ ..., home_testimonials[]->{content, jobTitle, author} }

Jul 21, 2021, 7:28 AM

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?