GraphQL 查询 ID 以外的内容

GraphQL to query something other than ID

我正在使用 Strapi 和 Nuxt.js 来实现我的第一个 Headless CMS。我正在使用 Apollo 和 GraphQL。

我 运行 遇到了当前的错误,我好几天都没有解决这个问题。

如果我写:

query Page($id: ID!) {
  page(id: $id) {
    id
    slug
    title
  }
}

并传递以下变量:

{
  "id" : "1"
}

我收到了正确的预期结果:

{
  "data": {
    "page": {
      "id": "1",
      "slug": "/",
      "title": "Homepage"
    }
  }
}

但是,我不想通过 ID 获取内容,而是通过我在 Strapi 中创建的一个名为“slug”的字段。 环顾四周,似乎我应该能够做这样的事情:

query Page($slug: String!) {
  page(slug: $slug) {
    id
    slug
    title
  }
}

有变量:

{
  "slug" : "/"
}

但我收到此错误:

{
  "error": {
    "errors": [
      {
        "message": "Unknown argument \"slug\" on field \"page\" of type \"Query\".",
        "locations": [
          {
            "line": 2,
            "column": 8
          }
        ],
        "extensions": {
          "code": "GRAPHQL_VALIDATION_FAILED",
          "exception": {
            "stacktrace": [

...错误继续....

[UPDATE] Italo回复后,我改成:

query Pages($slug: String!) {
  page(where: {slug: $slug}) {
    id
    slug
    title
  }
}

但我现在收到以下错误:

{
  "error": {
    "errors": [
      {
        "message": "Unknown argument \"where\" on field \"page\" of type \"Query\".",

我还注意到,如果我将“page”更改为“pages”,我会收到一个查询,但它会显示所有页面...

我错过了什么? 谢谢!

要使用除主键以外的其他方式查询一个项目(并且仅使用 Strapi 的默认内置查询),您需要使用可用的过滤器作为 where 子句:

query Pages($slug: String!) {
  pages(where: {slug: $slug}) {
    id
    slug
    title
  }
}

Tip: use the Graphql interface avaiable in http://localhost:1337/graphql to test that. (if you are not already)

这似乎对我使用 slug 有用

创建新文件 schema.graphql.js api/blog-post/config/schema.graphql.js

module.exports = {
  query: "blogPostBySlug(slug: String!): BlogPost",
  resolver: {
    Query: {
      blogPostBySlug: {
        description: "Return blog post with a given slug",
        resolver: "application::blog-post.blog-post.findOne",
      },
    },
  },
};

将 api/blog-post/config/routes.json 中的 routes.json 从 "path": "/blog-posts/:id" 更改为 "path": "/blog-posts/:鼻涕虫:

{
  "method": "GET",
  "path": "/blog-posts/:slug",
  "handler": "blog-post.findOne",
  "config": {
    "policies": []
  }
},