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

Invalid foreign key relationship:




LIST<Account> Alist=[SELECT id,name,(SELECT contact.FirstName,Contact.Lastname FROM account.contacts) FROM account
                     Where industry='environmental'];

System.debug('The Account Details:'+Alist[0]);
System.debug('The Account Name is:'+Alist[0].Name);
System.debug('The Associated Contact FirstName is:'+Alist[0].contact.FirstName);

In the above code through a error:Invalid foreign key relationship:


it is Parent to child retrieve single record.






The error is in the last line.

It should be :

System.debug('The Associated Contact FirstName is:'+Alist[0].contacts[0].FirstName);

There are multiple contacts in a single account.

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.
Dongzhi YangDongzhi Yang
Thanks Satish, 
I had the code below it didn't work. After I saw your post I realized that the index for child object is missing.
--------wrong code, missing index---
List<Account> accs = [SELECT Name,(SELECT LastName FROM Contacts) FROM Account];
--------right code, with index------------
List<Account> accs = [SELECT Name,(SELECT LastName FROM Contacts) FROM Account];
Hope this helps more beginners.