Can hasRole() be used inside of a loop?

a99920
Kilo Contributor

I am familiar with using it in reference to the current user using either g_user or gs but I am wanting to use it inside of an addQuery against my user table. Basically the goal is to walk through each user and determine if they have a role (and if they do we will execute a command). I am having issues using this against my variable I create however.

1 ACCEPTED SOLUTION

venkatiyer1
Giga Guru

Hi Joe,



Using the addquery method on sys_user for roles wont fetch the roles for the given user. roles column in sys_user is not referenced. The information of the association between the roles table and user table lies in sys_user_has_role   table or alternatively we can use the shortcut method of hasRole().



So we need to query against the sys_user_has_role  



var role= new GlideRecord('sys_user_has_role   ');



role.addQuery('user', sysid of user);



role.query();


View solution in original post

14 REPLIES 14

venkatiyer1
Giga Guru

Hi Joe,



hasRole can be used inside a while loop after you have queried for the user object. Alternatively, you can query on roles column and use the glide add query with CONTAINS.


Using the addQuery would be my preferred method. Here is my sample code...perhaps I am missing something here:




var user = new GlideRecord('sys_user');



user.addQuery('roles', 'CONTAINS', 'timecard_user');



user.query();



warren_chan
ServiceNow Employee
ServiceNow Employee

Within script, I believe hasRole() can only be used against GlideSystem (gs). You'd probably want to query the sys_user_has_role table directly as that would give you a clear relationship between user record and role record.



If you're having trouble with a variable, please post your code sample.


Agree with Warren, sys_user_has_role is a better table to access to get the roles for the concerned user.