graphql 嵌套查询
介绍 (Introduction)
In this tutorial, we’ll take an in-depth look at queries in GraphQL so that you better understand how to retrieve data from a GraphQL server. We will cover fields, arguments, aliases, operation syntax, and more. Once you have finished, you will be able to leverage the functionality of queries to build better API’s with GraphQL.
在本教程中,我们将深入研究GraphQL中的查询,以便您更好地了解如何从GraphQL服务器检索数据。 我们将介绍字段,参数,别名,操作语法等。 完成后,您将能够利用查询功能来通过GraphQL构建更好的API。
领域 (Fields)
GraphQL based on asking for specific fields on objects. We therefore can’t successfully talk about queries without talking about Fields. Queries are the construct used by the client to request specific fields from the server.
GraphQL基于请求对象上的特定字段。 因此,如果不谈论字段,就无法成功谈论查询。 查询是客户端用来从服务器请求特定字段的构造。
Given that GraphQL is structured to optimally expose one endpoint for all requests, queries are structured to request for specific fields, and the server is equally structured to respond with the exact fields being requested.
鉴于GraphQL的结构可以为所有请求最佳地公开一个端点,查询的结构可以请求特定的字段,服务器的结构也同样可以响应所请求的确切字段。
Consider a situation where a client wants to request for soccer players from an API endpoint. The query will be structured like this:
考虑一种情况,客户希望从API端点请求足球运动员。 查询的结构如下:
{
players {
name
}
}
This is a typical GraphQL query. Taking a closer look, queries are made up of two distinct parts:
这是一个典型的GraphQL查询。 仔细研究一下,查询由两个不同的部分组成:
The
root field
(players) : The object containing the payload.root field
(玩家):包含有效负载的对象。The
payload
(name) : The field(s) requested by the client.payload
(名称):客户端请求的字段。
This is an essential part of GraphQL because the server knows exactly what fields the client is asking for and always responds with that exact data. In the case of our example query, we could have this response:
这是GraphQL的重要组成部分,因为服务器确切地知道客户端要查询的字段,并始终以该确切的数据进行响应。 对于我们的示例查询,我们可以得到以下响应:
{
"players": [
{"name": "Pogba"},
{"name": "Lukaku"},
{"name": "Rashford"},
{"name": "Marshal"}
]
}
The field name
returns a String type, in this case, the names of the Manchester United players. However, we are not limited to just Strings: we can have fields of all data types, just like the root field players
returns an array of items. Feel free to learn more about the GraphQL Type System in the GraphQL official docs.
字段name
返回String类型,在这种情况下为曼联球员的名称。 但是,我们不仅限于字符串:我们可以拥有所有数据类型的字段,就像根字段players
返回项数组一样。 随意在GraphQL官方文档中了解有关GraphQL类型系统的更多信息。
In production, we would want to do more than just returning names. For instance, in our last query, we can redefine the query to select an individual player from the list and query for more data on that player. To be able to do so, we’ll need a way to identify that player so we can get the details. In GraphQL, we can achieve this with Arguments.
在生产中,我们不仅要返回名称,还希望做更多的事情。 例如,在上一个查询中,我们可以重新定义查询