This is a personal preference I have while writing queries.
Suppose a simple use case where you have request number and you want to update linked catalog tasks. First solution would be to query request table, get request's sys ID. Then run another database query to use this information to query associated requested items. Once the requested item details are found, use another (more than one depending on the number of requested items) query to fetch associated tasks. So the code would be something like below
var scRequest = new GlideRecord("sc_request");
scRequest.addQuery("number", "REQ0000001");
scRequest.query();
if(scRequest.next()) {
var scReqItem = new GlideRecord("sc_req_item");
scReqItem.addQuery("request", scRequest.getValue("sys_id");
scReqItem.query();
while(scReqItem.next()) {
var scTask = new GlideRecord("sc_task");
scTask.addQuery("request_item", scReqItem.getValue("sys_id");
scTask.query();
while(scTask.next()) {
scTask.comments = scRequest.comments.getJournalEntry(1);
scTask.update();
}
}
}
Although the solution works, we are making 3+ server side calls. A better solution would be to reduce the number of database calls. We can do so by using dot-walking in the conditions itself. Directly query on task table, use an addQuery like below.
var scTask = new GlideRecord("sc_task");
scTask.addQuery("request_item.request", "request_number");
scTask.query();
while(scTask.next()) {
scTask.comments = scTask.request_item.request.comments.getJournalEntry(1);
scTask.update();
}
This will pull in all the related tasks by using one database query.
Comments
Post a Comment