Quick Dynamic apex question here. I have a list of generic SObjects and I'd like to dynamically get the child share records (I have queried for them previously):

for( SObject rec : records ){
    for( SObject share : (List<SObject>)(rec.get('Shares')) ){ .... }

This code compiles, but when I try to run it, I get the following error:

System.SObjectException: Invalid field Shares for CustomObjectName__c

Where CustomObjectName__c is the name of my custom object.

I've used rec.get() before many times, but is it not supported for child share records?

I'm using the generic SObject approach, as I'm building a sharing utilities class for multiple types of SObject.

1 Answer 1


SObject.get(fieldName) returns the value for the field specified by fieldName. Shares is the relationship name, it isn't a field of your custom object, that's why you got that error.

In a parent-to-child query, if you want to extract the child records you must use getSObjects(relationshipName):

This method is primarily used with dynamic DML to access values for associated objects, such as child relationships.


// This could be a dynamic query
List<Sobject> accounts = [SELECT Name, (SELECT Id FROM Shares) FROM Account];
for (Sobject acc : accounts) {
    for (Sobject share : acc.getSObjects('Shares')) {
  • You're right, apologies! I should have had more caffeine and read the documentation more thoroughly. Thank you for your time.
    – Bigears
    Sep 11, 2023 at 14:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .