Sigurd Heggemsnes
Developer who loves making life easier for people
Sigurd is located at Oslo, Norway
Get parents parent in reference filter
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
}
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.
Developer who loves making life easier for people
Open editor and preview pane in split view all the time
Go to Open editor and preview pane in split view all the timeOrder by last name
Go to Use GROQ to order by last name in where name is stored as full name