function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
swain 10swain 10 

Please review my code logic for fetching all child and grand child account from a parent account page

Hey , this is the logic which I thought to fetch all child and grand child account(Multilevel) from a parent account page.

List<Account> acct= [Select Id , Name , Parentid from Account group by parentid];
Set<Id> Ids = new Set<Id>();
List<String> childAcctIds = [Select Id, (Select Id  from ChildAccounts) from Accounts where id:=apexpages.currentpage().getparameters().get(‘id’)];
Ids.addAll(childAcctIds);
for(Account acc: acct){
           if(acc.parentid != null){
             List<String> allChildIds = [Select id from Account where parentid IN : Ids];
             Ids.addAll(allChildIds);
                                   }
                       }
List<String> oppListOfAllChild = [Select Name ,(Select Id , Name from Opportunity) from Account where Id IN : Ids];
Steven NsubugaSteven Nsubuga
List<Account> acct= [Select Id , Name , Parentid from Account order by parentid];
Set<Id> Ids = new Set<Id>();
List<Account> childAcctIds = [Select Id, (Select Id from ChildAccounts) from Account where id:=apexpages.currentpage().getparameters().get('Id')]];
//Ids.addAll(childAcctIds);
for(Account childAcctId: childAcctIds){
    Ids.add(childAcctId.Id);
 }    
for(Account acc: acct){
           if(acc.parentid != null){
             List<Account> allChildIds = [Select id from Account where parentid IN : Ids];
             for(Account childId: allChildIds){
                Ids.add(childId.Id);
             }  
               //Ids.addAll(allChildIds);
                                   }
                       }
List<Account> oppListOfAllChild = [Select Name ,(Select Id, Name from Opportunities) from Account where Id IN : Ids];

 
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi

If you need child and grand child accounts you can query as below:
 
Map<Id,Account> childAccnts =new Map<Id,Account>([select id,parentId,name from Account where parentId=: apexpages.currentpage().getparameters().get(‘id’)]);

List<Account> grandchildAccnts = [select id,parentId,name from Account where parentId in: childAccnts.keySet()];

Thanks.
swain 10swain 10
Hey all, 
Thanks for all the reply.
I have just one confusion in all the above code ,Is there a limitation upto 3rd level child only? If yes , Is there any way to get all child , grand child , great grand child and so on upto bottom?

Thanks in advance.