graphql查询SQL父子关系 [英] graphql query SQL parent child relationship

查看:144
本文介绍了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父子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆