I created an apex class that updates a child record every time I update a parent record. Working fine, but heard that queries should not happen inside for loops. Any help, especially sample codes to make things clearer, will be greatly appreciated.
Apex Class
public class NewClass {
public static void NewMethod(List<Parent__c> newParent) {
newParent = [SELECT Id, Name, Field1__c, Field2__c WHERE Id IN: newParent];
List<Child__c> childQry = new List<Child__c>();
List<Child__c> childListToUpdate = new List<Child__c>();
for(Parent__c p : newParent) {
childQry = [SELECT Id, Name, Parent__c, Field1__c, Field2__c FROM Child__c WHERE Field1__c =: p.Id];
for(Child__c c : childQry) {
if(p.Id != null) {
c.Field2__c = p.Field2__c;
childListToUpdate.add(c);
}
}
}
update childListToUpdate;
}
}
Apex Trigger
trigger NewTrigger on Child__c (after update) {
if(Trigger.isAfter && Trigger.isUpdate) {
NewClass.NewMethod(Trigger.New);
}
}
Updated Apex Class
public class NewClass {
public static void NewMethod(List<Parent__c> newParent) {
Map<Id,List<Child__c>> parentToChildren = new Map<Id,<List<Child__c>>>();
List<Child__c> childrenToUpdate = new List<Child__c>();
for(Child__c child : [SELECT Id, Name, Parent__c, Field1__c, Field2__c FROM Child__c WHERE Field1__c =: p.Id]) {
if (!parentToChildren.containsKey(child.Parent__c)) {
parentToChildren.put(child.Parent__c, new List<Child__c>());
parentToChildren.get(child.Parent__c).add(child);
}
}
for(Parent__c p : newParent) {
List<Child__c> children = parentToChildren.get(p.Id);
for(Child__c c : children) {
c.Field2__c = parentToChildren.get(c.Parent__c).Field2__c;
childrenToUpdate.add(c);
}
}
update childrenToUpdate;
}
}
List<Child__c>
that contains all the child records if you want to update them. Or flatten it at the end.List
that would hold all the child records to be updated. Is it okay if you check it again and let me know if I am doing it correctly?