【问题标题】:building tree datastructure form mysql table recursion issue从mysql表递归问题构建树数据结构
【发布时间】:2018-11-19 14:04:27
【问题描述】:

我正在尝试从存储在自引用的 mysql 表中的数据构建递归结构形式,这意味着某些行可以成为其他行的父行,这是我拥有的演示数据

结果树应该是一棵树,它显示了孩子和父母之间的关系以及我设法生成的代码 问题是 bio4 缺少它的子 bio5 我认为问题在于,当我们在同一级别有两个 sup 父母时 第一个工作正常,但是当递归结束并回溯到其他级别时,第二个子级别的父级变为空 到目前为止,这是我在 express 中的主要路线中的代码,我还使用了 knex.js 和 accesscontrol.js 模块

router.get('/',async  function (req, res, next) {
 const permission = ac.can(req.user.role).readAny("test");
 if (!permission.granted)
    res.status(401).send("Insufficient Permission");

 testgroups = await db(`servicegroups`).select("*","ServiceGroupId AS id","Name AS text ",db.raw(`(SELECT "root" ) AS type`) ).where("ServiceGroupType", '=', 2).andWhere("ParentId", '=', 0).andWhere("Deleted",'=',0).select();
 var result = [];
 for(i in testgroups){
    result.push(testgroups[i])
    await global.getTestChildrens(testgroups[i], db);         
 }
 res.render("admin/lis/tests/tests",{user:req.user , data:{testgroups:JSON.stringify(result) } })

});

也是主要功能 就像这样 请注意,global 只是我在系统中使用的一个全局变量,它有几个重要的函数可以使用,其中一个是递归函数,而 db 只是我的数据库连接的 knex 实例

global.getTestChildrens =async  function (entity,db) {

 childs = await db('servicegroups').select("*", "ServiceGroupId AS id", "Name AS text ", db.raw(`(SELECT "subroot" ) AS type`)).where("ParentId", '=', entity.ServiceGroupId).andWhere("Deleted", '=', 0);
 if(childs.length>0){
    entity.children = childs;
 }else{
    entity.type = "leaf";
 }
 for(i in childs){        
    if (childs[i]){
        await global.getTestChildrens(childs[i], db);
    }else{
        console.log("undifened found :"+i)
    }
 }
 return entity;    
}

【问题讨论】:

  • 我已经写了使用变形做类似事情的答案。如果有兴趣,请查看this post 和其中链接的帖子。如果您遇到困难,我很乐意为您提供进一步帮助。
  • @user633183 感谢您的回复,这些很有帮助,但我仍然无法让代码正常工作:/返回具有相同级别的子树时它变成空的问题是什么

标签: javascript mysql node.js database recursion


【解决方案1】:

解决方案似乎很愚蠢,但解决方案是我把

const

在childs变量之前的关键字

getTestChildrens 

函数和解决的问题我改变了树的关系,它适用于所有测试用例

【讨论】:

    猜你喜欢
    • 2019-04-14
    • 2016-03-18
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 2015-04-26
    • 2011-11-25
    相关资源
    最近更新 更多