【问题标题】:GraphQL: Querying for a value from another table from a mutationGraphQL:从突变中查询另一个表中的值
【发布时间】:2019-07-10 04:11:49
【问题描述】:

假设我有一个表t1,它是另一个表t2 的外键。为简单起见,t2 只有列 'name' 和 'id' 都是唯一的。我将 id 存储在 t1 中。

我的问题是我想写一个我知道名字但不知道 id 的突变,当我去t1 中存储一些东西时。有没有办法在我的突变内部进行查询,以便它转换我语句中的值?

也许我可以将插件添加到我的项目中?

我最终得到类似这样的东西,我传递了一个已知名称,但我想存储 id

mutation addT1(
  $knownT2Name: String!,
) {
  createT1 (
    input: {
      t1: {
        id: $component
        # Is there a way to convert this to the id inside the query
        # Or do I need to query for the id with the name first then pass that in?
        t2_id: $knownT2Name
      }
    }
  ) {
    t1 {
      id
      t2_id
    }
  }
}

这是一个简单的例子。我不想用名称查询 id 的原因实际上是 t1 是外键到无数其他具有相同情况的表,我不想做 9+ 查询只是为了转换每个字符串到一个整数 id。

我更愿意做这样的事情:

mutation addT1(
  $knownT2Name: String!,
) {
  createT1 (
    input: {
      t1: {
        id: $component
        t2_id: t2Byt2(name: $knownT2Name) { id }
      }
    }
  ) {
    t1 {
      id
      t2_id
    }
  }
}

t2Byt2(name: $knownT2Name) { id } 是一个子查询,它传递名称并获取 id,然后将 id 存储在 't2_id' 中

我正在寻找一个用于 postgraphile (Here's the GitHub) 的嵌套突变插件,但我没有任何吸引力。这不是我想要的。

【问题讨论】:

    标签: graphql graphiql postgraphile postgraphql


    【解决方案1】:

    对于简单的关系,我相信你想要这样的东西:(使用嵌套突变插件)。这仅适用于 CREATE。 UPSERT 不走运。

    mutation addT1($t1Name: String!, $t2Name: String!) {
      createT1(
        input: { 
          T1: { 
            name: $t1Name, 
            t2ToT2: { connectByT2: { name: $t2Name } }
          }
        }
      ) {
        t1 {
          t1Id
          name
          t2ByT2 {
            name
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 2018-09-17
      • 2021-12-21
      • 2022-01-17
      • 2017-08-24
      • 2016-01-14
      • 2022-06-23
      • 2017-12-27
      • 2020-06-17
      相关资源
      最近更新 更多