Trigger logic to count the child records
Sigiloso
trigger CountChildRecords on Child_Object__c (after insert, after update, after delete, after undelete) { // Set to store parent IDs Set parentIds = new Set(); // Collect parent IDs from child records if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) { for (Child_Object__c child : Trigger.new) { if (child.Parent_Object__c != null) { parentIds.add(child.Parent_Object__c); } } } if (Trigger.isDelete) { for (Child_Object__c child : Trigger.old) { if (child.Parent_Object__c != null) { parentIds.add(child.Parent_Object__c); } } } // Query child records grouped by parent Map childCounts = new Map(); for (AggregateResult result : [ SELECT Parent_Object__c parentId, COUNT(Id) recordCount FROM Child_Object__c WHERE Parent_Object__c IN :parentIds GROUP BY Parent_Object__c ]) { childCounts.put((Id) result.get('parentId'), (Integer) result.get('recordCount')); } // Update the parent records with the count List parentsToUpdate = new List(); for (Id parentId : parentIds) { Parent_Object__c parent = new Parent_Object__c(Id = parentId); parent.Child_Count__c = childCounts.containsKey(parentId) ? childCounts.get(parentId) : 0; parentsToUpdate.add(parent); } if (!parentsToUpdate.isEmpty()) { update parentsToUpdate; } }