2016-08-04 137 views
0

我有一个Postgres的表表示与父子表层次:graphql查询SQL父子关系

表(类别):

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 
     ... 

回答

2

您实际上可以通过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 
     } 
    }) 
}); 

而且我得到了这样的结果:

enter image description here


请注意,我定义field财产作为功能,而不是一个简单的对象。定义为对象的field属性将失败,并且不允许您在字段中使用categoryType变量,因为在执行期间它不存在。

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

嗨,这种方法需要使用查询。如果用户不知道孩子有多深,该怎么办?我的问题是,这可以实现自动循环通过孩子吗? – XxXk5XxX

0

在SQL数据库之上使用GraphQL的困难之一是协调两个范例。 GraphQL是分层。 SQL数据库是关系。两者之间并不总是有明确的映射关系。

我们开源了一个框架,Join Monster,它具有建立模式的独特方式。如果这样做,它会自动为您生成SQL查询。它的核心思想是关系。从理论上讲,您可以在GraphQL查询中实现任意深度。