Newer Version Available
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'].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 Contact[] cons = a.Contacts;
5}
6
7//The following example also works because we limit to only 1 contact
8for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts LIMIT 1)
9 FROM Account
10 WHERE Name = 'testAgg']) {
11 Contact c = a.Contacts;
12}