我有一个 postgres 表,它表示具有父子表的层次结构:
表(类别):
id name parentId
1 CatA null
2 CatB null
3 CatC 1
4 CatD 1
5 CatE 3
期望的结果:
categories:
[
{
name: "CatA",
children: [
{
name: "CatC",
children: [
{
name: "CatE",
children: []
}]
},
{
name: "CatD",
children: []
}
],
},
{
name: "CatB",
children: []
}
]
问题是我不知道有多少级别,所以我无法查询如下内容:
category {
name
parent {
name
parent {
name
...
实际上,您可以使用 GraphQL 实现潜在的无限递归。因此,如果您不知道您的模式有多深入,它并不介意。
我能够用这个模式重现您想要的结果。我希望它可以帮助你:
const categories = [
{
name: 'CatA',
children: [
{
name: 'CatC',
children: [
{
name: 'CatE',
children: []
}]
},
{
name: 'CatD',
children: []
}
]
},
{
name: 'CatB',
children: []
}
];
const categoryType = new GraphQLObjectType({
name: 'CategoryType',
fields: () => ({
name: { type: GraphQLString },
children: { type: new GraphQLList(categoryType) }
})
});
const queryType = new GraphQLObjectType({
name: 'RootQuery',
fields: () => ({
categories: {
type: new GraphQLList(categoryType),
resolve: () => categories
}
})
});
我得到了这个结果:
请注意我定义field
财产作为function而不是一个普通的对象。这field
定义为对象的属性将失败并且不允许您使用categoryType
字段中的变量,因为在执行时它不存在。
fields: () => ({
...
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)