+ Start a Discussion

How can i traverse to multiple child from ultimate parent in trigger

Hello All,

I have a requirement like in each account record there is a amount field, i would like to SUM of total amount & store into the ultimate parent.

As of nw, i can able to get ultimate parent using trigger but i dont knw how to traverse from ultimate to child levels.

Agustin BAgustin B
Hi VSK98, if every account is going to have an Ultimate parent then you can make it a master-detail instead of a lookup and in the ultimate parent you can create a roll-up summary field to sum the amounts of each account under the Ultimate Parent.
if you still need the trigger try something like this:
trigger ultimateAccount on Account(after insert, after update) {
    Set<ID> setID = new Set<ID>();
    List<Account> lstAcc = new List<Account>();
        for(Account c : trigger.new){
    if(setid.size() > 0){
        lstAcc = [Select id,totalSum__c,(Select id,value__c from childAccounts__r) from Account where id IN : setID];
    for(Account acc : lstAcc){
		integer val = 0;
        for(Account con : acc.childAccounts__r){
            val += con.value__c;
        acc.totalSum__c= val;
    update lstAcc;

if it hels please like and mark as correct as it may help others asking the same.
Bryan Leaman 6Bryan Leaman 6
If you're using the native Account.ParentId field to define an account hierarchy, then it's going to be tricky, and you probably won't be able to use related records queries.

Are you starting from the ultimate parent and needing to re-accumulate all levels beneath the parent account?
Do you have intermediate levels where you need intermediate totals?  e.g. ...
    '----> Middle_Company
                 '-----> Tiny_Company_1
                 '-----> Tiny_Company_2
    '----> Another_Company
Does "Big_Parent_Company" need to be the total of all 4 of the others and does "Middle_Company" need to be a total for the two "Tiny_Company_?" records or do you only want a total for Big_Parent_Company and nothing for Middle_Company?

Basically, I'd create a set of parent Ids I need and then query all companies that have ParentId in :setOfParentIds. 
However, if there's a mult-level structure, you then need to add the new Account Ids to the :setOfParentIds and re-run the query. Any time you get Accounts whose Ids are not already in the setOfParentIds, you'll have to add the account Ids and re-run the query.

As you're re-querying the accounts you can build a map of AccountId -to- ParentAccountId. If you only care about the ultimate parent,  when adding an account to the map, if the parent Id is already in the map, use the parent's parent from the map rather than the parent listed directly on the account.