【问题标题】:Graphql - How to perform where clauseGraphql - 如何执行 where 子句
【发布时间】:2018-07-21 17:32:29
【问题描述】:

我是 graphql 的新手,我正在为查询而苦苦挣扎。 我想通过他们的电子邮件地址返回用户

我有一个类型定义调用 V1User,它有以下字段 ID, 电子邮件, 密码, 角色

此查询需要更改哪些内容才能根据电子邮件返回用户?

    query GetAllV1User {
  viewer {
     allV1Users{
      edges {
        node {
          id
          email
          role
          createdAt
          modifiedAt
        }
      }
    }
  }
}

我试过这个查询

    query getV1UserQuery($email: String!) {
  getV1User(email: $email) {
    id
    email
  }
}

使用这些参数

{"email": "test@test.com"}

但是得到以下错误

    {
  "errors": [
    {
      "message": "Unknown argument \"email\" on field \"getV1User\" of type \"Query\".",
      "locations": [
        {
          "line": 2,
          "column": 13
        }
      ],
      "name": "GraphQLError"
    },
    {
      "message": "Field \"getV1User\" argument \"id\" of type \"ID!\" is required but not provided.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "name": "GraphQLError"
    }
  ]
}

我的架构如下

Name        Type        Constraints 
id          ID          NonNull Unique  
modifiedAt  DateTime    NonNull 
createdAt   DateTime    NonNull 
role        String      NonNull 
password    String      NonNull 
email       String      NonNull Unique Indexed  

谢谢

这个查询解决了我的问题

query getUserForEmailAddressAndPassword($where: V1UserWhereArgs) {
  viewer {
    allV1Users(where: $where) {
      edges {
        node {
          email
          id
          createdAt
          password
          modifiedAt
          role
        }        
      }
    }
  }
}

连同这些查询变量

{"where": {"email": {"eq" : "test@test.com"}, "password": {"eq":"te2st"}}}

【问题讨论】:

  • 要做到这一点,您必须修改您的查询以获得一些参数。然后在解析器中发送请求中的参数。
  • 刚刚更新了我遇到的错误问题
  • 您能否提供此查询的架构代码?
  • 我正在使用 scaphold.io 创建架构 - 我可以将您添加到我的帐户以查看它吗?
  • 我从未使用过 scaphold,但我相信您可以查看架构代码,因此可以将其发布在这里。无论如何,我的第一个猜测是您需要在架构中更新 getV1UserQuery 查询

标签: graphql graphql-js


【解决方案1】:

您可以使用 where 子句和比较运算符来做到这一点。

https://hasura.io/docs/latest/graphql/core/databases/postgres/queries/query-filters.html#the-where-argument

query {
   authors (where: {articles: {rating: {_gt: 4}}}) {
     id
     name
     articles (where: {rating: {_gt: 4}}) {
       id
       title
       rating
     }
   }
 }

【讨论】:

  • 这应该是公认的答案。谢谢。
  • 同意,这应该是公认的答案,这实际上回答了原始问题。
【解决方案2】:

我不建议在您的过滤子句中使用字符串“where”。不要试图模拟 SQL。您要使用 where 子句过滤什么。如果它是电子邮件地址,则架构中的查询应包含用户作为字段,电子邮件作为该字段的参数。 因此,您发送的第一个示例是正确的方法。 此外,避免使用 getUsers 或 getUser 等动词声明查询。架构应该只使用名词声明查询

Query
{
   Users(email:String):[User!]
}

type User 
{
    id
    email
    createdAt
    otherStuff
}

【讨论】:

  • " 不要试图模仿 SQL" - SQL 使用英语,以熟悉语法和句子结构的风格(对于那些可以读/写英语的人),所以您不妨说“以一种对您的团队来说更难理解和合作的方式而不是更简单的方式来做这件事”。简洁和简洁是有价值的,只要它们不删除意义或使听众更难理解这个想法。我已经用 GraphQL 获得了大约一周的介绍性乐趣,而且每一次都有一些不直观、没有记录、故意模棱两可或从规范中省略的东西。
猜你喜欢
  • 2021-02-04
  • 2023-01-05
  • 1970-01-01
  • 2011-09-07
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多