【问题标题】:GraphQL Filter on Enum Column枚举列上的 GraphQL 过滤器
【发布时间】:2019-12-18 10:48:19
【问题描述】:

下面是我从 Strapi 后端获取帖子的 GraphQL 查询。

请注意,我在我的 Nuxt 应用上运行此程序。

现在我只想带上那些有post_status = "Publish"的帖子

post_status 是一个 ENUM 字段,有两个选项作为草稿和发布

query GetPosts{
  posts {
    id
    post_title
    post_excerpt
    post_featured_image{url}
    post_content
    post_category{category_name}
    postingredients{ingredient{ingredient_name}, ingredient_unit}
    updated_at
    post_author{username}
    post_slug    

  }
  }

我不明白我怎样才能得到

  1. 如何在我的原始查询中添加 post_status
  2. 如何过滤 post_status 我只能获得已发布的帖子。

    query GetStatusEnum{      
        __type(name: "ENUM_POST_POST_STATUS") {
        name
        enumValues {
          name
        } }          }
    

以上结果:

{
  "data": {
    "__type": {
      "name": "ENUM_POST_POST_STATUS",
      "enumValues": [
        {
          "name": "Publish"
        },
        {
          "name": "Draft"
        }
      ]
    }
  }
}

【问题讨论】:

    标签: graphql strapi


    【解决方案1】:

    我有一个类似的场景(虽然我也使用了 Prisma 层,所以请记住这一点),我不确定您是否可以在调用中过滤枚举值,但您可以过滤它返回的内容。

    const posts = [the array of all posts]
    
    const isPublished = (post) => {
        if (post.post_status.includes('Publish')) {
            return post;
        }
    }
    
    let publishedPosts = posts.filter(isPublished);
    
    return publishedPosts;
    

    【讨论】:

      【解决方案2】:

      要在您的原始请求中添加您的post_status,您只需将其添加到您要获取的属性列表中。

      {
        posts {
          id
          post_title
          post_status <- here /!\
        }
      }
      

      这是获取 Posts 的查询,其中 Publishpost_status

      {
        posts(where: { post_status: "Publish" }) {
          id
          post_title,
          post_status
        }
      }
      

      您可以在您的 Strapi 应用程序中使用 GraphQL Playground:

      http://localhost:1337/graphql

      您将在页面右侧看到一个 docs 按钮,该按钮将向您显示创建 GraphQL 请求所需的所有信息。

      【讨论】:

      • 不幸的是,这行不通。即使我认为这会很容易。以下是您得到的错误。 "message": "应为 \"ENUM_POST_POST_STATUS\" 类型的值,但收到:\"2\"",
      • 奇怪,我创建了一个全新的应用程序,它运行良好。但我不确定是否遵循您尝试执行的查询...您的 2. 点。
      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2019-08-14
      相关资源
      最近更新 更多