简体   繁体   English

Graphql-如何根据字段的条件获取结果?

[英]Graphql- How to fetch result based on the condition of a field?

I have a query that look like this:我有一个看起来像这样的查询:

query MyQuery {
  products {
    edges {
      node {
        featured
        id
        image {
          altText
          mediaItemUrl
          slug
        }
        productId
        name
        onSale
        
      }
    }
  }
}

What I want is only fetch the result that featured field is true , if the featured is false, then it never shown in the result.我想要的只是获取 feature 字段为true的结果,如果featured featured false,则它永远不会显示在结果中。

Something like query like below in mysql:类似于 mysql 中的如下查询:

SELECT id,image,name, featured FROM products WHERE featured = 'false'

But in graphql query above, I can't query the featured = false.但是在上面的graphql查询中,我无法查询到featured = false。

I tried:我试过了:

query MyQuery {
  products {
    edges {
      node {
        featured @include(if: false)
        id
        ... other field I need
        
      }
    }
  }
}

But what this query do is, if featured field is true, then included the featured field in the result, else don't included the field in the result.This is not what I want.但是这个查询的作用是,如果featured字段为真,则在结果中包含featured字段,否则不包含在结果中的字段。这不是我想要的。

What I want is,我想要的是,

If featured field of a product is true , then include the products into the result, else, remove the whole product from the result.如果产品的featured字段为true ,则将products包含在结果中,否则从结果中删除整个产品。

How can I achieve this in the MyQuery above?如何在上面的MyQuery中实现这一点?

The @include and @skip directives are used for field selection, not filtering. @include@skip指令用于字段选择,而不是过滤。 GraphQL has no built-in way of doing filtering, sorting or pagination. GraphQL 没有内置的过滤、排序或分页方式。 It's up to each individual service to implement these features by exposing the appropriate arguments.通过公开适当的 arguments 来实现这些功能取决于每个单独的服务。

In this case, products could expose an argument named filter or isFeatured to add the ability to filter the results by the featured value.在这种情况下, products可以公开一个名为filterisFeatured的参数,以添加按featured值过滤结果的能力。 The field's resolver should then use that argument value to determine the correct value to return.然后,该字段的解析器应使用该参数值来确定要返回的正确值。

If you're writing client queries and consuming a schema you did not write, check your API's documentation to determine what arguments are available for the products field.如果您正在编写客户端查询并使用您未编写的模式,请检查您的 API 文档以确定哪些 arguments 可用于products字段。 If the schema doesn't expose this capability and you don't have a way to change it, then as a client you don't have many options.如果架构没有公开此功能并且您没有办法更改它,那么作为客户端,您没有太多选择。 At best, you can handle the filtering yourself after the result is fetched, but this is troublesome if you also use pagination.充其量,您可以在获取结果后自己处理过滤,但是如果您还使用分页,这很麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM