+ Start a Discussion
praveen venkatapraveen venkata 

Want to print contact record firstname using parent to child relation query

list<account> acc_list=[select Id,name,Industry,Rating,(select ID,firstname,lastname
from account.contacts) from account where phone='abc122'];
system.debug(acc_list);
for(account a:acc_list)
{
system.debug(contacts.firstname);    // ERROR: Field doesnt exists
}

Best Answer chosen by Admin (Salesforce Developers) 
Satish_SFDCSatish_SFDC

You have to again loop in the contacts list

 

list<account> acc_list=[select Id,name,Industry,Rating,(select ID,firstname,lastname
from account.contacts) from account where phone='abc122'];
system.debug(acc_list);
for(account a:acc_list)
{
for(Contact c : a.Contacts){ system.debug(c.firstname);
} }

 

Each account has a list of contacts, so you loop through them and print.

 

Regards,
Satish Kumar
Please mark my answer as a solution if it was helpful so it is available to others as a proper solution.
If you felt I went above and beyond, please give me Kudos by clicking on the star icon.