Skip to main content

GraphQL API 高级查询

¥Advanced queries for the GraphQL API

Strapi 的 GraphQL API 可以自动解析许多查询,但复杂的数据访问可能需要更深入的关系提取或链接解析器。本简短指南介绍如何处理此类高级场景。

¥Strapi's GraphQL API resolves many queries automatically, but complex data access can require deeper relation fetching or chaining resolvers. The present short guide explains how to handle such advanced scenarios.

有关更多信息,请参阅 GraphQL 自定义 文档。

¥For additional information, please refer to the GraphQL customization documentation.

多级查询

¥Multi-level queries

使用嵌套选择集来获取多层级关系,如下例所示:

¥Use nested selection sets to fetch relations several levels deep, as in the following example:

{
restaurants {
documentId
name
categories {
documentId
name
parent {
documentId
name
}
}
}
}

GraphQL 插件会自动解析嵌套关系。如果你需要在特定级别应用自定义逻辑,请为该字段创建自定义解析器。

¥The GraphQL plugin automatically resolves nested relations. If you need to apply custom logic at a specific level, create a custom resolver for that field.

解析器链

¥Resolver chains

自定义解析器可以调用其他解析器以复用现有逻辑。一种常见的模式是在父解析器中解析权限或上下文数据,然后将其传递给子解析器,如下例所示:

¥Custom resolvers can call other resolvers to reuse existing logic. A common pattern is to resolve permissions or context data in a parent resolver and pass it down to child resolvers, as in the following example:

/src/api/restaurant/resolvers/restaurant.ts
export default {
Query: {
restaurants: async (parent, args, ctx) => {
const documents = await strapi.documents('api::restaurant.restaurant').findMany(args);
return documents.map(doc => ctx.request.graphql.resolve('Restaurant', doc));
},
},
};

在此示例中,父解析器使用 文档服务 API 获取餐厅信息,然后委托给插件提供的生成的 Restaurant 解析器,因此字段选择等默认行为仍然适用。

¥In this example the parent resolver fetches restaurants using the Document Service API, then delegates to the generated Restaurant resolver provided by the plugin so default behavior such as field selection still applies.

聚合钻取

¥Aggregation drilldowns

中继样式 连接会公开一个 aggregate 字段。你可以使用它来显示高级指标,同时允许用户深入查看特定分组。将 groupBy 与分页变量结合使用,以保持响应较小:

¥Relay-style connections expose an aggregate field. You can use it to show high-level metrics and still let users drill into a specific group. Combine groupBy with pagination variables to keep responses small:

query RestaurantsByCity($first: Int, $after: String) {
restaurants_connection(pagination: { limit: $first, start: $after }) {
aggregate {
groupBy {
city {
key
connection(pagination: { limit: 5 }) {
aggregate {
count
}
nodes {
documentId
name
}
}
}
}
}
}
}

使用查询变量在用户选择分组时调整嵌套分页。Strapi 在服务器端运行聚合,因此客户端只会下载所需的摘要行:即使处理大型数据集,这也能确保仪表盘的响应速度。

¥Use query variables to adjust the nested pagination when a user selects a group. Strapi runs the aggregation on the server, which is why the client only downloads the summary rows it needs: this keeps dashboards responsive even with large data sets.