graphql查询SQL父子关系

编程入门 行业动态 更新时间:2024-10-26 18:23:13
本文介绍了graphql查询SQL父子关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个postgres表,该表代表带有父子表的层次结构:

I have a postgres table that represents a hierarchy with a parent child table:

表格(类别):

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: [] } ]

问题是我不知道有多少级,所以我无法查询类似的内容:

The problem is that I don't know how many levels there are, so I can't query something like:

category { name parent { name parent { name ...

推荐答案

您实际上可以使用GraphQL实现潜在的无限递归.因此,如果您不了解自己的模式有多深入,那么也就不用介意了.

You can actually achieve the potential infinite recursion with GraphQL. So it doesn't mind if you don't know how deep you go with your schema.

我能够使用此架构重现您想要的结果.我希望它可以对您有所帮助:

I was able to reproduce your desired result with this schema. I hope it might helps you:

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属性定义为函数,而不是普通对象.定义为对象的field属性将失败,并且不允许您在字段中使用categoryType变量,因为在执行时该变量不存在.

Please notice that I define field property as a function rather than an plain object. The field property defined as object would failed and wouldn't allow you to use categoryType variable in the fields, because in the time of execution it doesn't exist.

fields: () => ({ ... })

更多推荐

graphql查询SQL父子关系

本文发布于:2023-10-25 00:14:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:父子   关系   graphql   SQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!