0

I'm working on a function that does a series of .getSObject() calls from an Account record to get three fields from one of the related records.

The issue I'm having is one of the fields returns a SObject row was retrieved via SOQL without querying the requested field error when doing the .get(), but the other two work fine.

This is what each call looks like, with a different field retrieved each time (account is an Account record that gets passed in):

SObject r = account.getSObject('Related1__r');
String test = (String) r.getSObject('Related2__r').get('fieldName__c');

It's not clear from Salesforce documentation what the object returned from .getSObject() and why it works fine for two fields but fails for the third. I can do a dynamic SOQL query to retrieve the same record that should be returned from the Related2__r .getSObject() call and then do a .get() on the exact same field but when I try to do the code snippet above for that particular field, it fails. It seems as if the .getSObject() only retrieves a subset of the fields, and in my case it doesn't include the field I need.

2
  • 2
    It should depend on which fields you're querying (as the error may suggest). What does your query look like? and what are the actual field/relationship names here?
    – Derek F
    Commented Oct 18, 2022 at 23:49
  • But what query? On the original Account object way up the chain? How does that determine what fields get retrieved from the related records? Sorry I am fairly new to SFDX. The actual names are custom, not OOTB. Commented Oct 18, 2022 at 23:54

1 Answer 1

5

The getSObject method returns all fields in memory. The following two lines should function identically:

SObject related = account.Related2__r;
// or
SObject related = account.getSObject('Related2__r');

If you are getting the error:

SObject row was retrieved via SOQL without querying the requested field

It means your SOQL does not include Related2__r.RequestedField__c. Double check your top level SELECT clause. Every field included in the below SELECT clause would carry over:

SELECT
    Related2__r.Field1__c,
    Related2__r.Field2__c,
    Related2__r.Field3__c
FROM Account

However, if you tried to reference Related2__r.Field4__c, you would encounter this error.

3
  • I see. Is there a way to dynamically include other fields, or will I need to amend the original query? Commented Oct 19, 2022 at 0:29
  • 1
    The query needs to include any fields you de-reference.
    – Adrian Larson
    Commented Oct 19, 2022 at 0:31
  • Are the two lines in your first snippet equivalent in turns of performance as well? I.e. is one going to perform slower than the other, or does one count against any of the limiters? Commented Oct 19, 2022 at 4:42

You must log in to answer this question.

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