Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

content management system - Sanity.io GROQ query for array of objects

I'm learning to code and now I am on the stage of a small pet project with Sanity as a CMS. Long story short, making an API I'm trying to fetch cocktails data with votes for the cocktails. The votes are stored within persons who voted:

GROQ query

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

which returns

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

As you can see, the merge provides embedded arrays of votes meanwhile I want sth like:

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

Trying to get this I modified the query:

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

which should take a projection from every element of the votes arr. Unfortunately I get empty arrays:

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

How can I achieve the desired result? Thank you for reading! Would appreciate any help!

question from:https://stackoverflow.com/questions/65905974/sanity-io-groq-query-for-array-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, had similar struggles with "flattening" the projections my self. I solved it with dot-syntax. Try just adding .votes on your first attempt:

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

If this is correct, the whole query can be simplified but I'm not at the level, yet, where I can do that without testing against a similar set ,'-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...