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.