You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS+Sanity博客:GROQ动态参数查询分类关联文章

解决Sanity GROQ查询动态分类slug的问题

直接解决方案(单个分类slug)

简化查询逻辑,直接判断动态参数是否存在于文章的分类slug数组中,无需多余的count和数组包装:

*[_type == "post" && $slug in category[]->slug.current] {
  _id,
  title,
  date,
  excerpt,
  coverImage,
  "slug": slug.current,
  "author": author->{name, picture},
  "categories": category[]-> {name, slug}
}

传递参数保持原有格式即可:

{
  $slug: 'travel' 
}

扩展方案(支持多分类slug查询)

如果需要一次性查询多个分类下的文章,可将参数改为数组类型,用overlaps语法实现多值匹配:

查询代码

*[_type == "post" && $slugs overlaps category[]->slug.current] {
  _id,
  title,
  date,
  excerpt,
  coverImage,
  "slug": slug.current,
  "author": author->{name, picture},
  "categories": category[]-> {name, slug}
}

参数示例

{
  $slugs: ['travel', 'dogs'] 
}

原查询失败原因

你之前的写法count((category[]->slug.current)[@ in [$slug]]) > 0存在冗余逻辑,GROQ中直接用$slug in category[]->slug.current就能完成单个值的存在性判断,额外的数组包装和计数操作反而容易引发语法层面的隐性问题,简化后即可正常工作。

内容的提问来源于stack exchange,提问作者Rohan Büchner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:01:04