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
Steve BerleySteve Berley 

Generically access child records in a parent-child query

I have a parent-child query where I need to use a generic approach to evaluating the results. This works great, except when trying to access the records from the child query.

In the example below:
  • 1 and 2 work and yield the same result, as you’d expect
  • 3 works perfectly
  • 4 errors with: "Invalid field Contacts for Account"
Any suggestions of how to access the child query generically?

Thanks,
list<account> aa = [SELECT name, ( SELECT name FROM Contacts ) FROM Account];
for (account a : aa) {
    system.debug('-- 1: '+a.name);
    system.debug('-- 2: '+a.get('name'));
    system.debug('-- 3: '+a.contacts);
    system.debug('-- 4: '+a.get('Contacts'));  // errors out
}
Best Answer chosen by Steve Berley
Abhishek BansalAbhishek Bansal
Hi Steve,

Since it is a list of sObjects so you should use getSobjects method instead of get.
a.getSobjects('Contacts');

Thanks,
Abhishek Bansal.

All Answers

Abhishek BansalAbhishek Bansal
Hi Steve,

Since it is a list of sObjects so you should use getSobjects method instead of get.
a.getSobjects('Contacts');

Thanks,
Abhishek Bansal.
This was selected as the best answer
Steve BerleySteve Berley
@Abishek - thank you!  I figured I was missing something simple but still I'm amazed how simple the solution was.