Sanity中引用对象数组问题求助:如何引用主题数组?
Sanity主题引用问题解决方案
你当前的错误在于:Sanity的reference类型仅支持引用独立的文档,不能直接引用同一文档内的数组字段项,你把array类型放进reference的to数组里,不符合Sanity的Schema规则,所以执行失败。
下面提供两种可行解决方案:
方案一:将主题设为独立文档(推荐,支持跨文档复用)
1. 创建独立的主题文档Schema
// schemas/articleTheme.js export default defineField({ name: 'articleTheme', title: 'Article Theme', type: 'document', fields: [ defineField({ name: 'name', title: '主题名称', type: 'string', validation: Rule => Rule.required() }), // 按需添加配色字段,比如背景色、文字色等 defineField({ name: 'backgroundColor', title: '背景色', type: 'color' }), defineField({ name: 'textColor', title: '文字色', type: 'color' }) ] })
2. 修改根节点的主题数组字段,改为引用独立主题文档
defineField({ name: 'articleThemes', title: '文章主题', description: '为文章区块选择4个主题', type: 'array', validation: (Rule) => Rule.required().max(4), of: [{ type: 'reference', to: [{ type: 'articleTheme' }] }], }),
3. 在目标区块中引用单个主题文档
defineField({ name: 'theme', title: '主题', type: 'reference', to: [{ type: 'articleTheme' }], // 可选:限制只能选当前文档已添加的主题 validation: Rule => Rule.custom((value, context) => { const docThemes = context.document?.articleThemes || [] if (value && !docThemes.some(theme => theme._ref === value._ref)) { return '所选主题必须是当前文章已配置的主题之一' } return true }) }),
方案二:主题仅属于当前文档(无需独立文档)
如果主题不需要跨文档复用,可直接基于当前文档的articletheme数组生成选择项,无需使用reference类型:
1. 确保articleThemeBlock包含唯一标识字段
// schemas/articleThemeBlock.js export default defineField({ name: 'articleThemeBlock', title: '文章主题区块', type: 'object', fields: [ defineField({ name: 'themeName', title: '主题名称', type: 'string', validation: Rule => Rule.required() }), // 其他配色字段... ] })
2. 在目标区块中使用string类型生成动态选项
defineField({ name: 'theme', title: '主题', type: 'string', validation: Rule => Rule.required(), options: { list: ({ document }) => { // 从当前文档的articletheme数组生成选择项 return (document?.articletheme || []).map(theme => ({ title: theme.themeName, value: theme._key // 用Sanity自动生成的_key作为唯一标识 })) } } }),
内容的提问来源于stack exchange,提问作者Tore
相关产品推荐
相关产品推荐

