Query in Loop problem: ( we do not need to to select query in loop ) - Domreysa

Post Top Ad

Post Top Ad

Monday, June 11, 2018

Query in Loop problem: ( we do not need to to select query in loop )

4. Query in Loop problem: ( we do not need to to select query in loop ) resolved:

In Apex Class:
public class UpdateAccTriggerHandler {

  public void handleBeforeCreateUpdate( List<Account> newAccList ){
     Set<Id> accountGroupIds = new Set<Id>();
      for( Account iAccount : newAccList ) {
            if(iAccount.Group__c != null ) {
                accountGroupIds.add( iAccount.Group__c );
            }

        }

       List<Account> accountGroups = [ SELECT Id, Name, OwnerId
                                  From Account
                                  WHERE Id in: accountGroupIds
                                ];

        Map<Id,Account> groupIdMap = new Map<Id,Account>();
        for( Account oneGroup: accountGroups ) {
            groupIdMap.put(oneGroup.Id,oneGroup);

        }

      for( Account iAccount : newAccList ) {
            if( iAccount.Group__c != null ) {
                iAccount.OwnerId = groupIdMap.get(iAccount.Group__c).OwnerId;
            }
        }
}
}

No comments:

Post a Comment

Post Top Ad

Responsive Ads Here