2

i am trying to build a recursive structure form from data stored inside mysql table which is self referenced, it means that some rows can become parents for others and this is a demo data that i have enter image description here

the resulted tree should be a tree that shows relations between child's an parents with my code i have managed to produce enter image description here the problem is that bio4 is missing its child bio5 i think the problem is that when we have two sup parents in the same level the first one is working properly but when the recursion ends and it backtracks to other levels the second sub level parent becomes null this is my code so far in my main route in express i used knex.js and accesscontrol.js modules also

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) } })

});

also the main function is like this Note that global is just a global variable that i use in my system which have couple of important functions to use one of them is the recursive function and db is just knex instance of my database connection

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;    
}
Aram Rafeq
  • 41
  • 8
  • 1
    I've written answers that do similar things using anamorphisms. If interested, check out [this post](https://stackoverflow.com/a/50121218/633183) and the posts linked within. If you get stuck, I'm happy to help you further. – Mulan Jun 10 '18 at 01:03
  • @user633183 thank you for your response those were helpful but i still cant get the code to work :/ what is the problem why when returning to subtrees which have same level it became null – Aram Rafeq Jun 10 '18 at 06:32

1 Answers1

0

the solution seems very stupid but the solution was that i put

const

keyword before childs variable inside

getTestChildrens 

function and the problem solved i changed the relations of the tree and it works with all test cases enter image description here

Aram Rafeq
  • 41
  • 8