首页 文章

graphql - 在突变中使用查询 - 创建嵌套对象

提问于
浏览
5

我有一个非常简单的模型 post 嵌入了几个 comments

我想知道我应该怎么做一个突变来添加一个新的 commentpost

由于我已经定义了一个查询以获取给定 idpost ,我想尝试使用以下变异语法

mutation {
  post(id: "57334cdcb6d7fb172d4680bb") {
    addComment(data: {
      text: "test comment"
    })
  }
}

但我可以't seem to find a way to make it work. Even if I'm在一个变异,输出类型是 post addComment被视为一个字段 post 应该有 .

你们有什么想法吗?

谢谢

3 回答

  • 0

    我可能错了,但你可能只想创建一个单独的updatePost变异,它接受post id作为参数

    type Post {
       comments: [ Comment ]
    }
    
    input PostInput {
       comments: [ CommentInput ]
    }
    
    type Mutation {
       updatePost( id: ID!, input: PostInput ): Post
    }
    

    这里的updatePost变异将post的id和更新的post对象作为参数,并返回Post类型 . 所以我会像这样使用它:

    mutation {
      updatePost( id: '1234', input: { comments: []) {
        id
      }
    }
    

    希望这可以帮助!

  • 0

    也许你可以创建 addComment 变异,你传递post id到然后返回一个帖子 .

    type Mutation {
       addComment( postId: ID!, input: CommentInput ): Post
    }
    
  • 0

    您无法将字段嵌入到其他字段中 .

    您将为后期突变创建一个新的输入对象

    input CommentInput {
     text: String
    }
    
    type Mutation {
     post(id: ID!, addComment: CommentInput): Post
    }
    

    在解析器中,您将查找addComment变量并使用参数调用addComment解析器 .

    你的突变会是

    mutation {
      post(id: "57334cdcb6d7fb172d4680bb", 
        addComment: {
          text: "test comment"
        }) {
        id
        comment {
          text
        }
      }
    }
    

相关问题