Fetch records using recursion

Denise3
Kilo Contributor

Suppose:

User1

User2 : Manager is User1

User3 : Manager is User2

User4 : Manager is User3

 

Fetch the records from user table using recursion

1 ACCEPTED SOLUTION

Yogi3
Kilo Guru

Try this code:

 

function getManager(userID){
var gr = new GlideRecord('sys_user');
gr.addQuery('sys_id',userID);
gr.query();
while(gr.next()){
if(gr.manager){
var output=getManager(gr.manager);
output=gr.manager.getDisplayValue()+' -> '+output;
return output;
}
else return null;
}
}

gs.print(getManager('02826bf03710200044e0bfc8bcbe5d3f')); //this is the sys_id of User 1

 

hope this help!

View solution in original post

4 REPLIES 4

Yogi3
Kilo Guru

Try this code:

 

function getManager(userID){
var gr = new GlideRecord('sys_user');
gr.addQuery('sys_id',userID);
gr.query();
while(gr.next()){
if(gr.manager){
var output=getManager(gr.manager);
output=gr.manager.getDisplayValue()+' -> '+output;
return output;
}
else return null;
}
}

gs.print(getManager('02826bf03710200044e0bfc8bcbe5d3f')); //this is the sys_id of User 1

 

hope this help!

Denise3
Kilo Contributor

I have tried this script but it is only working in Scripts- Background option. Applying in relationship on user table it's not working.

Subhojit Das
Kilo Guru

Hi Denise,

Below link may help you achieving your scenario,

https://community.servicenow.com/community?id=community_question&sys_id=caa14b69db98dbc01dcaf3231f96...

Note: Replace the tablename with sys_user and request with userID

Regards,

Subhojit

shivaniamborkar
Tera Expert

Hi All, 

I have solved this requirement using below code. 

 

function getManager(id){
     var gr = new GlideRecord('sys_user');
     gr.addQuery('sys_id', id);
     gr.query();

     var result;
     if(gr.next()){
         if(gr.manager){    //Shanna - Aileen - Amos - Angelique - Angelo
            result = getManager(gr.manager); 
            if(result==null){
               result = gr.manager.getDisplayValue();
            }
            return result;
         }
         else{
           return null;
         }
     }
}
function getUsername(id){
     var gr = new GlideRecord('sys_user');
     gr.addQuery('sys_id', id);
     gr.query();
     if(gr.next()){
        return gr.first_name + " " + gr.last_name;
     }
}

sysid='62826bf03710200044e0bfc8bcbe5df1';
gs.print(getUsername(sysid) + " : " + getManager(sysid));