Count the number of child records on the each parent record and then update on parent record field Total_child_count__c // Parent = Object1__c & Child = Object__C// They have a lookupRelation
trigger UpdateParentChildCount on Object__c (after insert, after update, after delete) {
// Get a set of all the parent IDs
Set<Id> parentIds = new Set<Id>();
for (Object__c child : Trigger.new) {
parentIds.add(child.Object1__c);
}
// Query for the count of child records for each parent
Map<Id, Integer> childCounts = new Map<Id, Integer>();
for (AggregateResult agg : [SELECT Object1__c, COUNT(Id) FROM Object__c WHERE Object1__c IN :parentIds GROUP BY Object1__c]) {
childCounts.put((Id)agg.get('Object1__c'), (Integer)agg.get('expr0'));
}
// Update the parent records with the child count
List<Object1__c> parentsToUpdate = new List<Object1__c>();
for (Id parentId : parentIds) {
Object1__c parent = new Object1__c(Id=parentId);
parent.Total_child_count__c = childCounts.get(parentId);
parentsToUpdate.add(parent);
}
update parentsToUpdate;
}
If this information helps, please mark the answer as best. Thank you
Hi Swetha,
Error = "
SELECT Object_1__c, COUNT(Id) FROM Object_2__c
^
ERROR at Row:1:Column:8
Invalid field: 'Object_1__c' "
Trigger :
trigger UpdateParentChildCount on Object_2__c (after insert, after update, after delete) {
Set parentIds = new Set();
for (Object_2__c child : Trigger.new) {
parentIds.add(child.Child_Of__c);
}
Map childCounts = new Map();
for (AggregateResult agg : [SELECT Object_1__c, COUNT(Id) FROM Object_2__c WHERE Object_1__c IN :parentIds GROUP BY Object_1__c]) {
childCounts.put((Id)agg.get('Object_1__c'), (Integer)agg.get('expr0'));
}
List parentsToUpdate = new List();
for (Id parentId : parentIds) {
Object_1__c parent = new Object_1__c(Id=parentId);
parent.Total_child_count__c = childCounts.get(parentId);
parentsToUpdate.add(parent);
}
update parentsToUpdate;
}
Can You Help me with this...?
i want update the total count on parent field when chiild record is deleted like if the value in total count field is 10 so when we delete 2 child record in child obj so it will date 10-2 =8. in the parent obj in total count filed Object_1__c is a parent
Try below trigger
If this information helps, please mark the answer as best. Thank you