【问题标题】:graphql - Refer to other fields in mutationgraphql - 参考突变中的其他字段
【发布时间】:2020-08-02 14:28:27
【问题描述】:

我想创建 2 个相关的对象,例如1 个位置和 1 个地方,其中地方引用了位置,如下所示:

type Location {
    id: String
    name: String
}

type Place {
    id: String
    locationId: String
}

是否可以通过 1 个突变请求来执行此操作?目前我正在使用 2 个单独的突变请求来执行此操作,如下所示:

mutation ($locationName: String!) {
  insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

//in another request, use the id returned from the request above
mutation ($locationId: String!) {
  insert_Place(objects: {locationId: $locationId}) {
    returning {
      id
    }
  }
}

我知道一个突变中可能有多个字段,因此我可以在 1 个突变请求中创建 2 个 Locations,如下所示。

mutation ($locationName: String!) {
  location1: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }

  location2: insert_Location(objects: {name: $locationName}) {
    returning {
      id
    }
  }
}

但是,如果我想创建 1 个位置和 1 个地点,有没有办法检索创建的位置 ID 并将其传递到第二个字段以创建地点?

【问题讨论】:

  • 听起来这2个数据类型是有关系的,请问这些表之间有外键关系吗? Hasura 允许您在 objects 参数内的其他表上插入新行,并在它们之间存在 FK 关系时负责连接它们
  • @Xetera 是的,Place.id 是 Location.id 的外键。啊,我刚刚找到了相关文档:hasura.io/docs/1.0/graphql/manual/mutations/…

标签: graphql apollo hasura


【解决方案1】:

供将来参考:

正如@Xetera 指出的那样,由于这两种类型具有外键关系,因此您可以进行嵌套插入突变,其中 hasura 将处理设置外键值。在我的情况下,它看起来像:

mutation ($locationName: String!) {
  insert_Place(
    objects: {
      Location: {data: {name: $locationName}}, //hasura will create Location and assign the id to Place.locationId
    }
  ) {
    returning {
      id
    }
  }
}

文档在这里进一步阅读:https://hasura.io/docs/1.0/graphql/manual/mutations/insert.html#insert-an-object-along-with-its-related-objects-through-relationships

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2020-02-25
    • 2018-08-30
    • 2016-06-30
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多