🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Get parents parent in reference filter

By Sigurd Heggemsnes

Get parents parent in reference filter

find-parents-parent.ts


interface FindParentsParentOptions {
  parentPath: Path
  document: SanityDocument
  level?: number
}

export const findParentsParent = ({
  parentPath,
  document,
  level = 1,
}: FindParentsParentOptions) => {
  if (level > parentPath.length) throw new Error("Level is too high")

  const obj = parentPath
    .slice(0, parentPath.length - level)
    .reduce((doc, path) => {
      if (typeof path === "object") {
        const t =
          Object.entries(path).length > 0 ? Object.entries(path)[0] : null
        if (!t) return doc
        const [property, value] = t
        return (doc as any).find((d: any) => d[property] === value)
      } else {
        return doc[path]
      }
    }, document)

  console.log("ParentsParents")
  return obj
}

article-by-category.ts

import { defineField } from "sanity"

export const articleByCategory = defineField({
  type: "object",
  name: "articleByCategory",
  fields: [
    defineField({
      type: "reference",
      name: "reference",
      to: [{ type: "category" }],
    }),
    defineField({
      type: "array",
      name: "articles",
      of: [
        defineField({
          type: "reference",
          name: "article",
          to: [{ type: "article" }],
          options: {
            filter: ({ document, parentPath }) => {
              const parentsParent = findParentsParent({
                parentPath: parentPath,
                document: document,
              })

              return {
                filter: "category._ref == $category",
                params: {
                  category: parentsParent.reference._ref,
                },
              }
            },
          },
        }),
      ],
    }),
  ],
})

Sometimes you want to get the "parents parent" when filtering references. This is a helper function to help you achieve that.

Can also be used by passing a "level" key so you can get X levels up from your current field.

Contributor

Other schemas by author