GraphQL-如何链接查询和变异? [英] GraphQL - How to chain queries and mutations?

查看:136
本文介绍了GraphQL-如何链接查询和变异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的graphQL模式中,我有两个对象之间的关系.说人与猫.

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

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

Humans have many Cats and Cats have one human.

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

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.

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

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

  1. 查询人类

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

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

  1. Build form with selection of humans on the client

发送创建新的猫突变

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

createCat(newCat: CatInput!) : String
`


// client

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

这篇关于GraphQL-如何链接查询和变异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆