+ Start a Discussion
Manish Anand 10Manish Anand 10 

Parent to Child Relationship:Issue

Hi,

I am trying to display all accounts, and for each account, the first and the last name of each contact associated with that account.
I am trying below APEX code.
List <Account> Res = [Select Account.Name, (Select Contact.FirstName,Contact.LastName from Account.contacts) from Account];
For(Account a:Res) {
//System.debug('Account Name:' +a.name);
//System.debug('Contact FirstName:' +contact.firstname); 
//System.debug('Contact Last Name:' +contact.LastName);  
}
 It displays the account name perfectly fine. But for Contact FirstName, it displays: FirstName , similarly for lastname it displays:LastName.
What, I am missing, here?
Best Answer chosen by Manish Anand 10
Mahesh DMahesh D
Hi Manish,

Use this code:
List <Account> Res = [Select Account.Name, (Select Contact.FirstName,Contact.LastName from Account.contacts) from Account];
For(Account a:Res) {
System.debug('Account Name:' +a.name);
    for(Contact con: a.Contacts) {
		System.debug('Contact FirstName:' +con.firstname); 
		System.debug('Contact Last Name:' +con.LastName);  
	}
}

Regards,
Mahesh

All Answers

venkat-Dvenkat-D
SOQL should be [Select Name, (Select FirstName,lastName form Contacts) from Account]
Manish Anand 10Manish Anand 10
Hi Venky,

I tried with the SOQL statement pasted above by you. It throws an error-unexpected token: Contacts
venkat-Dvenkat-D
[Select Name, (Select FirstName,lastName from Contacts) from Account]
Mahesh DMahesh D
Hi Manish,

Use this code:
List <Account> Res = [Select Account.Name, (Select Contact.FirstName,Contact.LastName from Account.contacts) from Account];
For(Account a:Res) {
System.debug('Account Name:' +a.name);
    for(Contact con: a.Contacts) {
		System.debug('Contact FirstName:' +con.firstname); 
		System.debug('Contact Last Name:' +con.LastName);  
	}
}

Regards,
Mahesh
This was selected as the best answer
Manish Anand 10Manish Anand 10
error-unexpected token: Contacts is fixed now. There was typo in the subquery.
However, the result is same as mentioned in my detail description. 
Any help?

Regards,
Manish.
venkat-Dvenkat-D
Do you have contacts associated for accounts?
venkat-Dvenkat-D
You can copy Mahesh code. That should work.
Mahesh DMahesh D
I tested the above code in my DE org and able to see the results as well.

Did you enable the Person Accounts?

http://resources.docs.salesforce.com/200/8/en-us/sfdc/pdf/salesforce_B2C_implementation_guide.pdf

Regards,
Mahesh
Manish Anand 10Manish Anand 10
Yes. Mahesh's code worked.
Thanks Again, Mahesh. 

Regards,
Manish.