需要帮助编写AWS AppSync(GraphQL)上的变更操作。

huangapple go评论77阅读模式
英文:

Need help writing mutation on AWS AppSync (GraphQL)

问题

这是您的 GraphQL 模式:

type Bird @model {
    id: ID!
    name: String!
    description: String!
    images: [String]
}

type Course @model {
    id: ID!
    name: String!
    description: String!
    image: String
    birds: [Bird] @hasMany
}

现在,您想要编写用于创建课程的变异。您可以像这样包括 Bird 对象数组:

mutation MyMutation2 {
  createCourse(input: {
    image: "",
    name: "",
    description: "",
    birds: [
      { name: "BirdName1", description: "BirdDescription1" },
      { name: "BirdName2", description: "BirdDescription2" }
      # 继续添加其他 Bird 对象
    ]
  }) {
    id
  }
}

只需在 birds 字段下包括一个对象数组,每个对象都包含所需的 namedescription 字段。

英文:

I have created this schema on GraphQL:

type Bird @model{
    id: ID!
    name: String!
    description: String!
    images: [String]
}

type Course @model{
    id: ID!
    name: String!
    description: String!
    image: String
    birds: [Bird] @hasMany
}

Now I want to write the mutation for createCourse. I don't know how to include the array of Bird object in my course.

I don't know how to add Bird object here:

mutation MyMutation2 {
  createCourse(input: {image: "", name: "", description: ""})
}

答案1

得分: 0

如果在Course模型中有@hasMany指令引用Bird模型,您应该在Bird模型中指定@belongsTo指令。
文档链接:https://docs.amplify.aws/cli/graphql/data-modeling/#belongs-to-relationship

因此,如果您想要一对多的关系,Bird模型应该如下所示:

type Bird @model{
  id: ID!
  name: String!
  description: String!
  images: [String]
  course: Course @belongsTo
}

这将在Bird模型中为Course创建一个新的关键字。

现在,在创建Course时,您无法添加Bird对象。您需要创建一个Bird,并引用@belongsTo创建的新关键字中的Course的id,以建立关系。

英文:

If you have a @hasMany directive referencing the Bird in a Course model, you should specify a @belongsTo directive in the Bird model.
Docs here: https://docs.amplify.aws/cli/graphql/data-modeling/#belongs-to-relationship

So your Bird model should look like this (if you want a 1 to many relationship)

type Bird @model{
  id: ID!
  name: String!
  description: String!
  images: [String]
  course: Course @belongsTo
}

This will create a new key for a Course in your Bird model.

Now, you can't add Bird objects when you are creating a Course. You need to create a Bird and there reference the id,in the new key created by @belongsTo, of the Course you want to relate to.

huangapple
  • 本文由 发表于 2023年6月9日 07:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定