I GlideQuery conditional where
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-15-2023 01:36 AM
I want to be able to include an additional where clause based on a condition, so I tried something like this
var gq = new global.GlideQuery('sys_user').limit(10).where('active', true);
if (role_required==true) gq.where(new global.GlideQuery().where('roles', 'itil').orWhere('roles', 'cmdb_read').orWhere('roles', 'knowledge'));
gq.orderBy('name');
var users = gq.select('name', 'user_name', 'department$DISPLAY').toArray(100);
However, the same results are returned regardless of whether role_required is true.
If I define the GlideQuery in a single statement:
var gq = new global.GlideQuery('sys_user').limit(10).where('active', true)
.where(new global.GlideQuery().where('roles', 'itil').orWhere('roles', 'cmdb_read').orWhere('roles', 'knowledge'))
.orderBy('name');
the expected results are returned - so i know the syntax is correct.
If I use toGlideRecord to extract the encoded query, I see that the conditional gq.where is always ignored.
Is it possible to add a where clause to a GlideQuery based on a condition?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-15-2023 02:02 AM
Did you check that your if condition is actually entered (maybe by adding a log statement inside)? For instance, are you sure you have a boolean value for role_required?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-15-2023 02:48 AM
Hello Laszlo
I put a breakpoint into the if-block and confirmed that the code is executed.
I also confirmed that this code DOES NOT WORK
var gq = new global.GlideQuery('sys_user').limit((_limit||10)).where('active', true).where('u_user_type', '1').where('u_staff_record_status', 'LIVE');
gq.where(new global.GlideQuery().where('roles', 'itil').orWhere('roles', 'cmdb_read').orWhere('roles', 'knowledge'));
but the same code works in the GlideQuery is defined in a single statement.