英文:
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
字段下包括一个对象数组,每个对象都包含所需的 name
和 description
字段。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论