I am new to salesforce. I am looking to bulkify the below code.
for (Account a: acc) {
List < Account > acclist = new List < Account > ();
Integer ChildCount;
String ParentIdVar;
List<Account> Acctest = New List<Account>();
accList = [select id, parentId, Name from Account where Id = : a.Id];
if(a.ParentId == null){
ParentIdVar = [select Id from Account where Id=:a.Id][0].Id;
Acctest = [select id, parentId, Name from Account where Id = : ParentIdVar];
AggregateResult[] child = [select count(Id)idcount from Account where ParentId =: a.Id];
ChildCount = Integer.valueOf(child[0].get('idcount'));
}
else If (a.ParentId != null){
ParentIdVar = [Select Id from Account where Id=:a.ParentId][0].Id;
Acctest = [select id, parentId, Name from Account where Id = : ParentIdVar];
AggregateResult[] child = [select count(Id) idcount from Account where ParentId =: a.Id or ParentId =: a.ParentId];
ChildCount = Integer.valueOf(child[0].get('idcount'));
}
String TempVal = AccTest[0].Id;
List<Account> ChildList = [select id, parentId, Name from Account where ParentId =:TempVal];
}
Thanks in advance.
13 answers
Hi Catherine,
You are executing SOQL queries from within a FOR loop, which makes the code not bulkified.
You would look to execute any queries and store the results in a Map collection before you enter the for loop, and then use .containsKey() and .get() to leverage the map collection in the logic inside your for loop.
What is the requirement you are working to meet? - a count of child accounts written to the parent?