Here is the sample Roll-up Summary calculation trigger for Lookup relationship. The below trigger do a Sum Operation using Aggregate Query.
Parent: Account
Child: Contact
Logic: Update parent record field called Total__c with Sum of all related child records Amount__c field value.
- trigger TotalAmountTrigger on Contact (after insert, after update, after delete, after undelete)
- {
- Set<Id> accountIds = new Set<Id>();
- for(contact c: Trigger.isDelete? Trigger.old : Trigger.new){
- if(c.AccountId != null)
- {
- accountIds.add(c.AccountId);
- }
- }
- List<Account> accList = new List<Account>();
- for(AggregateResult currentAggResult:[SELECT AccountId accId, SUM(Amount__c) sumAmt FROM Contact WHERE AccountId in:accountIds GROUP BY AccountId])
- {
- Account acc = new Account();
- acc.Id = (Id)currentAggResult.get('accId');
- acc.Total__c = (Decimal)currentAggResult.get('sumAmt');
- accList.add(acc);
- accountIds.remove((Id)currentAggResult.get('accId'));
- }
- for(Id currAccId : accountIds)
- {
- Account acc = new Account();
- acc.Id = currAccId;
- acc.Total__c = null;
- accList.add(acc);
- }
- update accList;
- }
Since there are two objects in the above scenario.
ReplyDeleteWhat if there is self relationship to the object itself. Say for example there is a self relationship on account object and 1 account can have multiple child account. In that case how to use the fields of child account??
Thanks in advance!!