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
Chamil MadusankaChamil Madusanka 

SOQL Issue

I have following code. I want to know that is there any other approach to rewrite the highlighted code segment? That highlighted code area is not obey for best practices because there is a query in a loop.

 

 

public class Hierarchy {

public Employee__c employee;
public List<Team__c> team;

public Hierarchy(ApexPages.StandardController stdController){
employee=(Employee__c)stdController.getRecord();
}

public String getEmmployees(){
team=[Select t.Name, t.Id, (Select Name, Employee_Name__c From Team__r) From Team__c t];

for(Team__c tm:team){

}
//System.Debug('TEAM :: '+team.Name);
//System.Debug('TEAM :: '+team.Team__r.size());


return null;
}

public List<TreeModel> nodeList {get;set;}
public Hierarchy(){
nodeList = new List<TreeModel>();

for(Division__c acc : [Select d.Name, d.Id, (Select Id, Name From Teams__r) From Division__c d LIMIT 1000]){



if(acc.Teams__r.size() > 0){
TreeModel tm = new TreeModel();
tm.id = acc.Id;
tm.name = acc.name;
for(Team__c cnt: acc.Teams__r){
TreeModel tmChild = new TreeModel();
tmChild.id = cnt.Id;
tmChild.Name = cnt.Name;
tm.children.add(tmChild);

for(Team__c acc1 : [SELECT id, Name, (Select Id, Name,Employee_Name__c from Team__r) from Team__c LIMIT 1000]){


TreeModel tm1 = new TreeModel();
tm1.id = acc1.Id;
tm1.name = acc1.name;
if(tm1.id.equals(tmChild.id)){

for(Employee__C cnt1: acc1.Team__r){
TreeModel tmChild1 = new TreeModel();
tmChild1.id = cnt1.Id;
tmChild1.Name = cnt1.Employee_Name__c;
tmChild.children.add(tmChild1);
}

}

}
}
nodeList.add(tm);
}
}

}

public class TreeModel{
public string id {get;set;}
public string name {get;set;}
public List<TreeModel> children {get;set;}

public TreeModel(){
children = new List<TreeModel>();
}

}



}

 Thanks & Regards

Chamil Madusanka

 

Best Answer chosen by Admin (Salesforce Developers) 
shra1_devshra1_dev

You can take the second query into a list and use that list in the enhanced for loop.

 

 

list<Team__c> lstTeams = [select id, name, (select id,name,Employee_Name__c from Team__r) from Team__c limit 1000];

 

In the Second for:

 

for(Team__c acc1: lstTeams){

//rest of ur code

}

 

This will eliminate the query in for loop but your code contain nested for this may cause max script stmts limit.

 

Regards,

Shravan