You need to sign in to do that
Don't have an account?
Aishwarya Londhe
How to remove soql query from for loop
Set<Id> accId= new Set<Id>(rootParentIdSet);
for(Integer counter = 0; counter < 7; counter++) {
         Map<Id, Account> accMap = new Map<Id, Account>([Select Id,ParentId from Account
         where ParentId In :accId);
       if(accMap != null && !accMap.isEmpty()) {
          accId= accMap.keySet();
          accIdSet.addAll(accId);
        }
      }
for(Integer counter = 0; counter < 7; counter++) {
         Map<Id, Account> accMap = new Map<Id, Account>([Select Id,ParentId from Account
         where ParentId In :accId);
       if(accMap != null && !accMap.isEmpty()) {
          accId= accMap.keySet();
          accIdSet.addAll(accId);
        }
      }
Not sure why you have accId= accMap.keySet(); as at firts place you are using accId in your query.
Â
You can simply add Map outside the for loop or else you can take list also.
If your requirement is to collect all account Id's which have parent account, You can try below code and check once.
Set<Id> accId= new Set<Id>(rootParentIdSet);
list<Account> lstAccs =[Select Id,ParentId from Account where ParentId In :accId]; // retrieving accont records where parent id in accId.
Set<Id> accIdSet= new Set<Id>();
for(Account acc: lstAccs ){ // iterating allaccounts one by one.
     accIdSet.add(acc.id); //every account id is adding to set.
}
Â
If my answer is helpful mark it as best answer.
Thanks & Regards,
Divya.
If the above one is not your requirement post your exact requirement again.
Thanks & Regards,
Divya.
Â