如何在 GROQ 中将内部联接作为条件?

How do I make a inner join as a condition in GROQ?

我有一个包含 posts 的数据集,它可能有一个类别数组。

如何进行 GROQ 查询以选择所有类别标题为 "Page" 的帖子?

我认为我可以做这样的事情:

*[_type == 'post' && categories[]->title == 'Page']{
  body,
  slug,
}

我可能需要使用函数在数组内进行匹配,但 the cheetsheet 对我来说太密集了 - 我就是找不到它。

我的数据集的要点是:

{
  {
    _createdAt: "2018-08-24T17:59:04Z",
    _id: "e84d78f0-81ed-4524-9c36-f38a1f1b2375",
    _rev: "1X9D03Y03BUslZ33alDJwF",
    _type: "category",
    _updatedAt: "2018-08-24T18:13:14Z",
    description: "Pages/Sider",
    title: "Page"
  },
  {
    _createdAt: "2018-08-26T21:57:54Z",
    _id: "3c023e29-b167-4021-be00-5e8dc14f65cc",
    _rev: "WQjjTjyYBRudo6JCOBCUj7",
    _type: "post",
    body: [
      {}
    ],
    categories: [],
  },
  {
    _createdAt: "2018-08-24T17:57:55Z",
    _id: "3d8f0c40-a45d-4dc7-ad95-ed1b49bca4af",
    _rev: "WQjjTjyYBRudo6JCO0spXR",
    _type: "post",
    body: [
      {}
    ],
    categories: [
      {
        _key: "491c03573205",
        _ref: "e84d78f0-81ed-4524-9c36-f38a1f1b2375",
        _type: "reference"
      }
    ]
  }
}

一个简单的查询:

*[_type == 'post']{
  //  body,
  "category": categories[]->title,
  //  slug,
  categories
}

Returns:

{
  categories: [],
  category: []
}

{
  categories: [
    {
      _key: "491c03573205",
      _ref: "e84d78f0-81ed-4524-9c36-f38a1f1b2375",
      _type: "reference"
    }
  ],
  category: [
    Page
  ]
}

根据 the join documentation,您可以在 GROQ 过滤器中使用内部联接。我认为这对您有用,前提是您的类别文档是 _type: "category" :

*[_type == 'post' &&
  *[_type == "category" &&
    title == "Page"][0]._id in categories[]._ref]{
   body,
   slug,
 }

希望这能解决您的问题!