How to count number of child records in lookup relationship in Salesforce?

How to count number of child records in lookup relationship in Salesforce?

Sample Trigger:

trigger HobbyTrigger on Hobby__c (after insert, after delete) {
    map<Id, Integer> mapEmpIdHobbyCount = new map<Id, Integer>();
    if(trigger.isInsert) {
        for(Hobby__c hob : trigger.new) {
            if(hob.Employee__c != null) {
                if(!mapEmpIdHobbyCount.containsKey(hob.Employee__c)) {
                    mapEmpIdHobbyCount.put(hob.Employee__c, 1);
                } else {
                    mapEmpIdHobbyCount.put(hob.Employee__c, mapEmpIdHobbyCount.get(hob.Employee__c) + 1);
                }
            }
        }
    } else {
        for(Hobby__c hob : trigger.old) {
            if(hob.Employee__c != null) {
                if(!mapEmpIdHobbyCount.containsKey(hob.Employee__c)) {
                    mapEmpIdHobbyCount.put(hob.Employee__c, -1);
                } else {
                    mapEmpIdHobbyCount.put(hob.Employee__c, mapEmpIdHobbyCount.get(hob.Employee__c) - 1);
                }
            }
        }
    }
    if(mapEmpIdHobbyCount.size() > 0) {
        List<Employee__c> listEmp = [SELECT Id, Number_of_Hobbies__c FROM Employee__c WHERE Id IN : mapEmpIdHobbyCount.keySet()];
        
        for(Employee__c emp : listEmp) {
            emp.Number_of_Hobbies__c += mapEmpIdHobbyCount.get(emp.Id);
        }
        
        update listEmp;
    }
}

Leave a Reply