Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Avoid updating same record twice when updating record on m2m table

Vidya Shree
Kilo Sage

Hi All,

 

I am writing a fix script to update records on the m2m table. Since its m2m relationship one record has multiple records linked to it(just like sys_user_has_role table).So, Whenever i am updating something it is updating the same record multiple times. How can i avoid this?

 

Thanks

Vidyashree

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@Vidya Shree 

it might be going into recursion

share your script along with screenshots.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

var m2m = new GlideRecord('sn_vul_m2m_vul_group_item');
m2m.addEncodedQuery('sn_vul_vulnerability.state=3^sn_vul_vulnerability.substate=22^sn_vul_vulnerable_item.state=3^sn_vul_vulnerable_item.substate=22^sn_vul_vulnerable_item.ignore_expirationISNOTEMPTY');
m2m.query();
while(m2m.next())
{
 
m2m.sn_vul_vulnerable_item.ignore_expiration = 'true';
m2m.sn_vul_vulnerable_item.work_notes = "Setting true";
m2m.updateWithReferences();
}

It's probably due to updateWithRefereces(), change to 'm2m.update(); and test:

 

 

updateWithReferences(Object reason)
Updates a record and also inserts or updates any related records with the information provided.

 

GlideRecordAPI_GlideRecord-updateWithReferences

 

Seem you will need to add logic to update the dot-walked fields.

Seems a dangerous API (updateWithReverences()) if table relationships are not known. using the example in the documentation, for a non-existing record:

 

var inc = new GlideRecord('incident');
inc.get(inc_sys_id);  // Looking up an existing incident record where 'inc_sys_id' represents the sys_id of a incident record
inc.caller_id.first_name = 'John';
inc.caller_id.last_name = 'Doe';
inc.updateWithReferences();

when run in Scripts - Background results in:

Screenshot 2024-12-17 161856.png

Showing affected tables. The View full summary link shows:

Screenshot 2024-12-17 184848.png