👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

How to create a reference filter in Sanity.io for selecting artwork based on the artist field.

3 replies
Last updated: May 17, 2022
Hello, I’m working on a reference filter so that a field ‘Artwork’ can filter its selection of artwork references based on the selection of the ‘Artist’ field in the same document. I looked at this documentation for dynamic filters (https://www.sanity.io/docs/reference-type#8118f73f6758 ) but I would need to get a more specific reference to the _id of another field. Has anybody else gone about doing this? Grateful for any tips thank you 🙂
May 12, 2022, 12:54 PM
I can get the artworks by a specific artist with a join like in the query below but I am curious about how I would bring this together with a filter on my reference field.
*[ _type == ‘artist’ && _id == ‘68133653-8d79-44c2-b801-066c9a146a2f’]{
‘artworksByArtist’: *[_type == ‘artwork’ && references(^._id)],
}
May 12, 2022, 12:56 PM
The filter option can take a function that receives the document within its props, so you can leverage the
_ref
of the field to get the
_id
of the document you're referencing.
Take the Movie database Sanity provides when you create a project via the CLI. The following will give me only movies which contain the selected actor within the array of cast members:

{
      name: 'actor',
      title: 'Actor',
      type: 'reference',
      to: [{ type: 'person' }],
    },
    {
      name: 'movie',
      title: 'Movie',
      type: 'reference',
      to: [{ type: 'movie' }],
      options: {
        filter: ({ document }) => ({
          filter: '$id in castMembers[].person._ref',
          params: {
            id: document.actor._ref,
          },
        }),
      },
    },
Depending on what your schema looks like, you'll likely want something like this:

{
      name: 'artist',
      title: 'Artist',
      type: 'reference',
      to: [{ type: 'artist' }],
    },
    {
      name: 'artwork',
      title: 'Artwork',
      type: 'reference',
      to: [{ type: 'artwork' }],
      options: {
        filter: ({ document }) => ({
          filter: '$id in artist._ref',
          params: {
            id: document.artist._ref,
          },
        }),
      },
    },
May 12, 2022, 6:41 PM
Ah I see! Thanks so much for this guidance
user M
🙏
May 17, 2022, 10:07 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?