GraphQL如何做一个JOIN请求而不是许多顺序请求? [英] GraphQL how to do a JOIN request instead of many sequential request?

查看:318
本文介绍了GraphQL如何做一个JOIN请求而不是许多顺序请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种GraphQL类型:

I have two GraphQL type:

type Author {
  id: String!
  name: String!
}

type Book {
  id: String!
  author: Author!
  name: String!
}

在我的数据库中,它是由books表中的外键实现的:

In my database, it is implemented by a foreign key inside the books table:

表格作者(伪代码)

`id` INTEGER UNSIGNED
`name` STRING

餐桌书(伪代码)

`id` INTEGER UNSIGNED
`author_id` INTEGER UNSIGNED REFERENCE `authors.id`
`name` STRING

因此,当我解析GraphQL查询时:

So when I resolve a GraphQL query like:

query allTheBooks {
  id
  name
  author {
    id
    name
  }
}

我只想执行一个SELECT SQL查询,例如:

I would like to do only one SELECT SQL query like:

SELECT books.id, books.name, authors.id, authors.name
FROM books
LEFT JOIN authors ON authors.id = books.author_id

代替当前:

SELECT books.id, books.name, books.author_id
FROM books

SELECT authors.id, authors.name
FROM authors
WHERE author.id = [one the the books.author_id of the first SELECT]

SELECT authors.id, authors.name
FROM authors
WHERE author.id = [one the the books.author_id of the first SELECT]

[...]

是否有办法知道在GraphQL解析器中查询了哪些子字段"?

Is there a way to know which "child fields" are queried in a GraphQL resolver ?

预先感谢您的回答!

推荐答案

我刚刚发现,在解析器提供的第四个参数中,有一个查询字段的数组:info.fieldNodes[0].selectionSet.selections.

I just discovered that in the fourth parameter gived at the resolver, there where an array of the queried fields: info.fieldNodes[0].selectionSet.selections.

我没有找到有关此文档的任何文档,而且我想知道什么代表fieldNodes数组...(并且不希望以这种方式访问​​第一个元素而不知道它...).

I didn't found any documentation about this, and I wonder what represent the fieldNodes array... (and dont like to access the first element that way without knowing it...).

selections对象包含这样的数组:

The selections object contains an array like this:

[
  {
    kind: 'Field',
    alias: undefined,
    name: { kind: 'Name', value: 'id', loc: [Object] },
    arguments: [],
    directives: [],
    selectionSet: undefined,
    loc: { start: 36, end: 38 }
  },
  {
    [...]
  },
  ...
]

在这里,value: 'id'与相关作者的查询字段名称匹配.

Here, the value: 'id' match the name of the queried field of the related author.

如果我深入研究,则selectionSet: undefined会成为对象,并且模式会以递归方式重复自身...

If I go a level deeped, the selectionSet: undefined becomes an object and the pattern repeat itself recursively...

这篇关于GraphQL如何做一个JOIN请求而不是许多顺序请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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