function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SainSain 

I have to count a child records on parent object by using trigger

Hi All,

I have a two objects like doctor(parent) and patient(child), my scenario is i have to count a child records on parent object by using trigger.

(using rollup summary we can achieve this but i have to achieve with trigger)

please any one help me with code for this scenario.

Thanks in advance!!!
Bob RobertsBob Roberts

Very curious requirement. To do this I am making the assumption that you have a field defined on the parent to hold the count. In general, it would go something like this:
 

Set<Id> ids = newMap.keyset();
for(ParentObj__c parent : newMap.values()){
    parent.Field__c = 0
}

for(ChildObj__c child: [SELECT ParrentObj__c FROM ChildObj__c WHERE ParrentObj__c IN :ids]){
    newMap.get(child.ParrentObj__c).Field__c++
}

update newMap.values();

Vatsal KothariVatsal Kothari
Hi Shaik,

you can refer below code:
trigger countChild on Child_Object__c (after insert,after update,after delete) 
{
	for (AggregateResult ar : [Select Count(Id) numRecs, Parent_Lookup_Field__c parentId From Child_Object__c Where Parent_Lookup_Field__c In :Trigger.New Group By Account__c ]) {
		Id parentId = (Id) ar.get('parentId');
		Parent_Object__c obj = Trigger.newMap.get(parentId);
		obj.Count__c = (Decimal) ar.get('numRecs');
	}
}
Replace API names with your Object and field API name.

If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal
James LoghryJames Loghry
Why can't this be done via a Rollup Summary?  Is it a Master Detail relationship or a Lookup relationship?
SainSain
Hi James,

Lookup relationship.
Ravikant Saini 1Ravikant Saini 1
List<ParrentObj__c> updatelist = new List<ParrentObj__c>();//you can use the parent id's as the place of newMap.keyset()
for(ParrentObj__c parent: [SELECT Id,(SELECT ID FROM ChildObj__c) FROM ParrentObj__c WHERE Id IN :newMap.keyset()])
{
    List<ChildObj__c> childList = parent.get('ChildObj__c');
    if(childList == null)
            parent.Field__c= 0;
    else
            parent.Field__c= childList.size();
     updatelist.add(parent);
}
update updatelist;
you can do it easily with nested query.

Demo User 45Demo User 45
Error: Compile Error: Illegal assignment from Object to LIST<Contact> at line 6 column 13
what to do