Groq: join to a document field

729 views Asked by At

I have a schema that reads something like this: a Page (document) has an array of Items (object); each Item can have a Post (document); each Post has several Tags (document).

I have got most of the drilling down working, but for some reason I can't quite work out the join on Tags. Here's an abridged look at my schema:


{ name: 'page',
  type: 'document',
  fields: [
    { name: 'title', type: 'string' },
    { name: 'slug', type: 'slug' },
    { name: 'items', type: 'array',
      of: [
        { type: 'itemImage' }, /* and a couple others */
      ],
    },
  ],
},

{ name: 'itemImage',
  type: 'object',
  fields: [
    { name: 'image',
      title: 'Image',
      type: 'image',
      validation: Rule => Rule.required(),
    },
    { name: 'post',
      type: 'reference',
      to: [
        { type: 'post' },
      ],
    },
  ]
},

{ name: 'post',
  type: 'document',
  title: 'Post',
  fields: [
    { name: 'title',
      type: 'string',
    },
    { name: 'tags',
      type: 'array',
      of: [
        { type: 'reference', to: [{type: 'tag'}] },
      ]
    },
  ],
},

{ name: 'tag',
  type: 'document',
  fields: [
    { name: 'tag', type: 'string' },
  ],
},

and here is my working query…

*[_type == "page" && slug.current == "home"] {
  'slug': slug.current, 
  title, 
  'gridItems': items[] {
    'src': image.asset->url,
    'title': post->title,
    'postLink': post->slug.current,
  }
}[0]

… so I have figured out how to query an array of objects, and how to query a referenced document, but I can't seem to bridge to querying an array of referenced documents. Any clues?

1

There are 1 answers

0
Eric_WVGG On

got it

*[_type == "page" && slug.current == "home"] {
  'slug': slug.current, 
  title, 
  'gridItems': items[] {
    'src': image.asset->url,
    'title': post->title,
    'postLink': post->slug.current,
    'tags': post->tags[]->{tag}
  }
}[0]