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
Big EarsBig Ears 

SObject row was retrieved via SOQL without querying the requested field - for child relationships?

Hey all,

I'm building a wrapper class and the argument need to include a record and its share records. via e.g.

Custom_Object__c c = [select id, Contact__c, Status__c, (select id, rowCause, ParentId, userOrGroupId, AccessLevel from Shares) from Custom_Object__c  where Contact__c IN :ContactIds]

ExampleWrapper e = new ExampleWrapper(c);

I'd like to throw a custom exception if the passed in record doesn't have the share records included. Is there a way to do that? There may be times where there are genuinely no Shares, so I can't just check for zero shares, I really need to check whether they were included in the SOQL query.

Additionally (just to make it more difficult), I can't enforce the SOQL by putting it in the Wrapper class. I'd like to avoid SOQL in the wrapper class, so it's bulk compatible.

I know that if a SOQL doesn't include a field that is needed later on, that produces an error, but the same thing doesn't appear to happen with child relationships. Does anybody know how?

Andy

Rahul KhilwaniRahul Khilwani
Hi Andy,

You can check if you are getting values in the child query using below statement:
 
if(c.getsObjects('Shares').size() >0){
    //code here.
}

Let me know if this works.

Regards
Rahul
Big EarsBig Ears

Rahul,

Unfortunately, I've realised that doesn't suit my requirement. The method "getSObjects('Shares")" returns a null if there are no shares, even if they've been included in the query.

I need to distinguish between whether or not the Shares were included in the SOQL query.

Thank you for the suggestion, though! I hadn't previously been aware of that method and it will come in handy elsewhere.

Andy