Understanding Foreign Key and Parent-Child Relationship SOQL Queries
The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example:
1System.debug([SELECT Account.Name FROM Contact
2 WHERE FirstName = 'Caroline' WITH USER_MODE].Account.Name);Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:
1for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
2 FROM Account
3 WHERE Name = 'Acme'
4 WITH USER_MODE]) {
5 Contact[] cons = a.Contacts;
6}
7
8//The following example also works because we limit to only 1 contact
9for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts WITH USER_MODE LIMIT 1)
10 FROM Account
11 WHERE Name = 'testAgg']) {
12 Contact c = a.Contacts;
13}