通过 Mutation 在 GraphQL 中创建连接对象

Create Connected object in GraphQL via Mutation

通过连接到另一个对象的突变创建对象的最佳做法是什么。

使用以下架构:

type Question @model {
  id: ID!
  text: String!
  answers: [Answer] @connection(name: "QuestionAnswers")
}
type Answer @model {
  id: ID!
  text: String!
  question: Question @connection(name: "QuestionAnswers")
}

以下(及其变体)失败:

mutation CreateAnswer {
  createAnswer(input: {
    text:"Yes",
    question: {
      id: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
    }
  }) 
    {
        id
    }
  }

服务器端代码:

mutation CreateAnswer($input: CreateAnswerInput!) {
  createAnswer(input: $input) {
    id
    text
    question {
      id
      text
      answers {
        nextToken
      }
    }
  }
}

通过上述,收到以下错误:

"Validation error of type WrongType: argument 'input' with value 'ObjectValue{objectFields=[ObjectField{name='text', value=StringValue{value='3'}}, ObjectField{name='question', value=ObjectValue{objectFields=[ObjectField{name='id', value=StringValue{value='9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8'}}]}}]}' contains a field not in 'CreateAnswerInput': 'question' @ 'createAnswer'"

这似乎是 AppSync 中的命名约定。以下对我有用:

mutation createAnswer {
  createAnswer (input: {
    text: "5"
    answerQuestionId: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
  }) {
    id
  }

answer 添加到 QuestionId 是所需要的。