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
SS KarthickSS Karthick 

Access Child Records in Parent-Child Relationship in apex

Hi folks,
       Can anyone tell me how to access the child records in parent child relationship?
My code snippet as follows
List<Account> acc = [SELECT Id,Name,(SELECT Id,LastName FROM Contacts) FROM Account];
for(Account  a: acc){
     System.debug('CAaount name:'+ a.Name);

//I dono how to acces contact s here
       for(Contact c:a.Contacts)
     { System.debug('Conatct Last:' +c.LastName);
     }


Thanks in advance,
Karthick
goabhigogoabhigo
You have posted answer by yourself. What else do you need?
List<Account> acc = [SELECT Id,Name,(SELECT Id,LastName FROM Contacts) FROM Account];
for(Account  a : acc){
     System.debug('CAaount name:'+ a.Name);
     for(Contact c : a.Contacts) { 
          // here you can access Contacts using the variable c, like what you have done, in debug statement
          System.debug('Conatct Last:' +c.LastName);
     }
}

--
Abhi

If my answer helps to solve the issue/problem/doubt, please mark it as Best Answer; so that people who are stuck in the similar issue get benefitted. 

 
SS KarthickSS Karthick
Hi goabhigo,
        am getting system.queryException: Invalid query locator.

 
goabhigogoabhigo
Looks like there are too many records in your org. Try putting a WHERE condition to filter the number of records.

To understand why this occurs, please go through - https://help.salesforce.com/apex/HTViewSolution?id=000004410&language=en_US (https://help.salesforce.com/apex/HTViewSolution?id=000004410&language=en_US)

--
Abhi
SS KarthickSS Karthick
@goabhigo
    My usecase is to fetch all the accounts and its assocaited contacts