【问题标题】:Update a column value in a Postgres table using Graphql mutation使用 Graphql 突变更新 Postgres 表中的列值
【发布时间】:2019-07-19 11:40:24
【问题描述】:

Basic info:后端使用 Postgres,前端使用 Postgraphile 使用 GraphQL。

Need:使用 GraphQL 突变更新 Postgres DB 中的一行。

Code: 假设我有一个 library_account 模式,它在 Postgres 中有 book 表,其中包含 id、title、borrower_id 和 is_available 等字段。

Scenario:这是第一次被借。

Proposed flow:进行 GraphQL 突变以使用 borrower_id 更新 Postgres 表。

我目前使用的代码:

mutation BookUpdates(
  $title: String,
  $borrower_id: Int!, #not really an Int but for the sake of ease.
  $author_id: Int!,
  $isle_id: Int!,
  $is_available: Boolean
) {
  updateBookByAuthorIdAndIsleId(input: {
    isle_id: $isle_id,
    is_available: $is_available,
    borrower_id: $borrower_id,
    author_id: $author_id
}) {
  bookEdge {
    node {
      author_id
    }
  }
}

在这里,我收到了borrower_id 的错误,它说borrower_id 不是由updateBookByAuthorIdAndIsleId 类型定义的。

有什么建议吗??

【问题讨论】:

    标签: database postgresql graphql mutation postgraphile


    【解决方案1】:

    在 GraphQL 中构建查询和突变时,通常明智的做法是使用 GraphiQL 等客户端,它可以通过提供文档、自动完成功能以及突出显示错误发生的位置来帮助您。 PostGraphile 内置了 GraphiQL;它在 CLI 上默认启用,但如果您在库模式下使用它,则必须通过 graphiql: true 来启用它。无论哪种方式,我都建议您使用 --enhance-graphiql / enhanceGraphiql: true 标志。如果您将突变放入 GraphiQL 中,它应该会告诉您哪里出了问题,甚至可能会建议如何修复它!

    在我看来,您的突变形状略有错误。 PostGraphile 遵循中继输入对象突变规范,这意味着我们将所有突变输入嵌套在输入参数下,就像您所做的那样。但是,我们还将有关记录的详细信息分组在一起,以便在进行更新时更容易将“什么”与“如何”分开 - 例如“what”:authorId: 27, isleId: 93,“how”:patch: {text: $text} - 这还允许您更新键(例如,如果您想更改 isleId),如果所有列都在一起,这是不可能的。我相信这是你缺少的部分。

    我怀疑你的变异应该更像:

    mutation BookUpdates(
      $borrower_id: Int!, #not really an Int but for the sake of ease.
      $author_id: Int!,
      $isle_id: Int!,
      $is_available: Boolean
    ) {
      updateBookByAuthorIdAndIsleId(input: {
        isleId: $isle_id,
        authorId: $author_id
        bookPatch: {
          isAvailable: $is_available,
          borrowerId: $borrower_id,
        }
    }) {
      bookEdge {
        node {
          authorId
        }
      }
    }
    

    我还对你的字段名称进行了驼峰命名,但如果你加载了自定义变形器,这可能不是必需的/不可取的。

    【讨论】:

    • 非常感谢,本杰。我最终使用了与此类似的东西,但我猜这也可以。此外,对于像我这样对 GraphiQL 非常陌生的人,您可以使用查询变量来测试这种突变!
    猜你喜欢
    • 2020-05-30
    • 2020-10-20
    • 2020-05-30
    • 2018-10-16
    • 2020-06-29
    • 2019-03-10
    • 2021-12-02
    • 2018-01-08
    • 2018-06-20
    相关资源
    最近更新 更多