subquerysoql

Reading results of a Sub Query in SOQL Salesforce


I am new to Apex and SOQL.

I want to get data from Account and Contacts of Contacts using SOQL , give the results to a List.

From the List, I want to 'Get' data from the results Outer Query Accounts and from the the inner query (from Contacts). How do I do this?

This is what I tried, I do not know how to proceed further.

integer counter = 0;
string accountId;
string accountName;
List<Account> myAccts = [SELECT Id, Name, (Select Id, Name from Contacts) from Account];
for(Account i :myAccts) {
    
    
    //System.debug(i);
  Account currentAccount =   myAccts.get(counter);
    
    accountId = currentAccount.Id;
    accountName = currentAccount.Name;
    System.debug('This is the current account record---' + accountName);
    counter = counter+1;
}

Solution

  • // SOQL to retrieve Accounts and related Contacts
    List<Account> myAccts = [SELECT Id, Name, (Select Id, Name from Contacts) from Account];
    
    // Loop through each Account
    for (Account acct : myAccts) {
       
        // Example of referencing Account field
        system.debug(acct.Name);
        
        // Loop through each related Contact
        for (Contact con : acct.Contacts) {
            
            // Example of referencing Contact field
            system.debug(con.Name);
        }
    
    }