这是一个很好的问题,因为它说明了 REST/RPC 样式 API 和 GraphQL 之间的显着差异。在 REST 风格的 API 中,您返回的对象仅包含有关如何获取更多数据的元数据,并且 API 使用者应该知道如何在这些表上运行 JOIN。在您的示例中,您需要使用 ID 属性加入 subtitle 和 translation。在 GraphQL 中,对象很少单独存在,关系编码到架构本身中。
您没有发布您的schema,但从外观上看,您创建了一个translation 对象和一个subtitle 对象,并在您的根查询中公开了它们。我的猜测是它看起来像这样:
const Translation = new GraphQLObjectType({
name: "Translation",
fields: {
id: { type: GraphQLInt },
lines: { type: Lines }
}
});
const SubTitle = new GraphQLObjectType({
name: "SubTitle",
fields: {
lines: { type: Lines }
}
});
const RootQuery = new GraphQLObjectType({
name: "RootQuery",
fields: {
subtitle: { type: SubTitle },
translation: { type: Translation }
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
您应该做的是与翻译INSIDE OF这样的字幕建立关系。 GraphQL 的目标是首先在您的数据中创建一个图表或关系,然后弄清楚如何向该数据公开入口点。 GraphQL 允许您在图中选择任意子树。
const Translation = new GraphQLObjectType({
name: "Translation",
fields: {
id: { type: GraphQLInt },
lines: { type: Lines }
}
});
const SubTitle = new GraphQLObjectType({
name: "SubTitle",
fields: {
lines: { type: Lines }
translations: {
type: Translation,
resolve: () => {
// Inside this resolver you should have access to the id you need
return { /*...*/ }
}
}
}
});
const RootQuery = new GraphQLObjectType({
name: "RootQuery",
fields: {
subtitle: { type: SubTitle }
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
注意:为清楚起见,我省略了参数字段和任何其他解析器。我相信你的代码会更复杂一点,我只是想说明这一点:)。