构建树数据结构表单mysql表递归问题

eagi6jfj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(357)

我试图从mysql表中存储的数据构建一个递归结构表单,mysql表是自引用的,这意味着一些行可以成为其他行的父行,这是我的一个演示数据

结果树应该是一个树,它用我的代码显示孩子和父母之间的关系

问题是bio4缺少它的子bio5,我认为问题是当我们在同一级别有两个sup父级时,第一个工作正常,但当递归结束并返回到其他级别时,第二个子级父级变为null这是我的代码,到目前为止,我在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;    
}
t5zmwmid

t5zmwmid1#

这个解决办法似乎很愚蠢,但解决办法是

const

关键字在childs变量之前

getTestChildrens

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

相关问题