2

我正在学习编码,现在我正处于一个以 Sanity 作为 CMS 的小型宠物项目的阶段。长话短说,制作一个 API 我正在尝试通过鸡尾酒投票来获取鸡尾酒数据。投票存储在投票的人中:

GROQ 查询

*[
  _type == "cocktail" &&
    !(_id in path('drafts.**'))
 ] {
  name,
  _id,
    "votes" : *[_type == "person" && references(^._id)] {
    votes[] {
        score,
        "id": cocktail._ref
        }
    } 
}

返回

[
  {
    "_id": "pdUGiuRzgLGpnc4cfx76nA",
    "name": "Cuba Libre",
    "votes": [
      {
        "votes": {
          "id": "pdUGiuRzgLGpnc4cfx76nA",
          "score": 2
        }
      },
      {
        "votes": {
          "id": "pdUGiuRzgLGpnc4cfx76nA",
          "score": 2
        }
      }
    ]
  },
  {
    "_id": "pdUGiuRzgLGpnc4cfxBOyM",
    "name": "The ERSH7",
    "votes": []
  }
]

如您所见,合并提供了嵌入式投票数组,同时我想要这样的东西:

[{
  ...cocktail attributes...
  "votes" : [
    {score: 2, id: pdUGiuRzgLGpnc4cfx76nA},
    {score: 2, id: pdUGiuRzgLGpnc4cfx76nA}
  ]
 }
... more cocktails....
]

试图得到这个我修改了查询:

*[
  _type == "cocktail" &&
    !(_id in path('drafts.**'))
 ] {
  name,
  _id,
    "votes" : *[_type == "person" && references(^._id)].votes[] {
        score,
        "id": cocktail._ref
    }
}

这应该从投票 arr 的每个元素中进行预测。不幸的是,我得到了空数组:

[
{
  "_id": "pdUGiuRzgLGpnc4cfx76nA",
  "name": "Cuba Libre",
  "votes": [
    {},
    {}
  ]
}
...more cocktails
]

我怎样才能达到预期的效果?感谢您的阅读!将不胜感激任何帮助!

4

2 回答 2

1

是的,在“扁平化”我自己的预测方面也有类似的挣扎。我用dot-syntax解决了它。尝试添加.votes您的第一次尝试:

*[
  _type == "cocktail" &&
  !(_id in path('drafts.**'))
]
{
  name,
  _id,
  "votes" : *[_type == "person" && references(^._id)] {
    votes[] {
      score,
      "id": cocktail._ref
    }
  }
  .votes
}

如果这是正确的,则可以简化整个查询,但我还没有达到这个水平,但是我可以在不针对类似集合进行测试的情况下做到这一点,'-)

于 2021-02-11T13:11:10.723 回答
0

实际上,从 v2021-03-25 开始,GROQ 具有展平数组的语法

找到这个例子:

{
  'nestedArray': [
    {'foo': [1,2,3,4,5]},
    {'foo': [6,7,8,9,10,11,12]},
    {'foo': [13,14,15]},
  ]
}{
  'stillNestedArray': @.nestedArray[].foo,
  'flatArray': @.nestedArray[].foo[]
}

请注意[]后面foo的内容-这就是将其展平的原因

所以问题的原始查询应该看起来像

*[
  _type == "cocktail" &&
    !(_id in path('drafts.**'))
 ] {
  name,
  _id,
    "votes" : *[_type == "person" && references(^._id)] {
    votes[] {
        score,
        "id": cocktail._ref
        }
    }.votes[] 
}
于 2022-01-22T16:54:31.767 回答