GraphQL-如何进行连锁查询和突变?[英] GraphQL - How to chain queries and mutations?

本文是小编为大家收集整理的关于GraphQL-如何进行连锁查询和突变?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在我的 graphQL 架构中,我在两个对象之间建立了关系.说人和猫.

人有很多猫,猫有一个人.

如果我想创建一个属于人类的新猫,我需要通过 ID 查询人类,然后我需要使用该 ID 进行突变以创建猫.

如何将这些链接在一起?看起来很简单,但找不到合适的例子.我也很可能以错误的方式思考这个问题.

推荐答案

我认为将它们链接起来没有意义.如果您想创建一只新猫,您需要一个列表,您可以在其中选择要将猫添加到的人类.因此,在发送突变之前,您已经必须查询人类.

猫的变异将包含选定的人类 id,过程可能如下所示:

  1. 查询人类

const getAllHumansQuery = gql`
query getAllHumans {
   getAllHumans {
      id
      name
   }
}
`;

  1. 在客户端选择人员构建表单

  2. 发送创建新的猫变异

// server
`
input CatInput {
  name: String!
  humanIds: [ID!]
}

createCat(newCat: CatInput!) : String
`


// client

const createCatMutation = gql `
  mutation createCat($newCat: CatInput!) {
    createCat(newCat: $newCat) {
      name
    }
  }
`;

本文地址:https://www.itbaoku.cn/post/1938063.html

问题描述

In my graphQL schema, I have a relationship between two objects. Say Humans and Cats.

Humans have many Cats and Cats have one human.

If I want to create a new Cat belonging to a human, I need to query for the human by ID and then I need to use that ID to do a mutation to create the cat.

How can I chain these together? It seems simple but can't find an appropriate example. It is also very likely that I'm thinking about this in the wrong way.

推荐答案

I don't think it makes sense to chain them. If you want to create a new cat you need a list where you select the humans you want to add the cat to. So you already have to query for the humans, before you send the mutation.

The mutation for the cat would contain the selected human ids, the process could look like this:

  1. query for humans

const getAllHumansQuery = gql`
query getAllHumans {
   getAllHumans {
      id
      name
   }
}
`;

  1. Build form with selection of humans on the client

  2. Send create new cat mutation

// server
`
input CatInput {
  name: String!
  humanIds: [ID!]
}

createCat(newCat: CatInput!) : String
`


// client

const createCatMutation = gql `
  mutation createCat($newCat: CatInput!) {
    createCat(newCat: $newCat) {
      name
    }
  }
`;