How to count number of child records - Relationship table

Paul125
Kilo Guru

I am trying to find out the number of childs that exist to a parent by gliding the relationship table, I am using the below script but result coming as 'undefined'.

var ciSysIds = ['09653fa7db4f9b00e0a45bc0cf96192c'];
var agg1 = new GlideRecord('cmdb_rel_ci');
agg1.addAggregate('count');
agg1.addQuery('parent','IN',ciSysIds);
agg1.addQuery('type.parent_descriptor','members');
agg1.addQuery('type.child_descriptor','member of');
agg1.groupBy('child');
agg1.query();
if(agg1.next()) {
var count = agg1.getAggregate('count');
gs.info(count);
1 ACCEPTED SOLUTION

Paul125
Kilo Guru
parentSysIds = agg.getValue('parent');
var agg1 = new GlideAggregate('cmdb_rel_ci');
agg1.addAggregate('count');
agg1.addQuery('parent','IN',parentSysIds);
agg1.addQuery('type.parent_descriptor','members');
agg1.addQuery('type.child_descriptor','member of');
agg1.groupBy('parent');
agg1.query();
if(agg1.next()) {
var count = agg1.getAggregate('count');
gs.info(count);
}

View solution in original post

8 REPLIES 8

Jaspal Singh
Mega Patron

Hi Ryan,

 

You can try below snippet (untested)

//var ciSysIds = '00e2c25037310200f212cc028e41f174';
var count=0;
var agg1 = new GlideRecord('cmdb_rel_ci');
agg1.addAggregate('count');
agg1.addQuery('parent','00e2c25037310200f212cc028e41f174');
//agg1.addQuery('type.parent_descriptor','members');
//agg1.addQuery('type.child_descriptor','member of');
agg1.groupBy('child');
agg1.query();
while(agg1.next()) 
{
count++;
}
gs.print('count is '+count);

Thanks,

Jaspal Singh

 

Hit Helpful or Correct on the impact of response.

Thanks for the reply Jaspal. My code was working after changing the GlideRecord to Aggregate but I am only seeing count as 1 when there are 5 childs to the CI that I am gliding for. Any thoughts?

Comment the 

agg1.groupBy('child');

 

Thanks,

Jaspal Singh

 

Hit Helpful or Correct on the impact of response.

Pradeep Sharma
ServiceNow Employee

Hello Ryan,

 

Replace GlideRecord with GlideAggregate in your script and try once.

 

Thanks,

Pradeep Sharma