You need to sign in to do that
Don't have an account?
Kevin Bromer
Safely check for child objects from soql
Hey all-
Have some soql like this:
Opportunity o = [select id (SELECT id from Opportunity.ChildObject__r) from Opportunity limit 1];
I want to reference the id on the first child object, so I do:
id myid = o.ChildObject__r[0].id;
However, if there is no ChildObject for Opportunity o, that throws a null reference exception. I tried checking it like this:
if (o.ChildObject__r[0] != null)
But that also produces a null reference exception.
I know o exists, and I know there are no ChildObjects for o (for this example). I'm sure I'm mising something obvious - any thoughts?
Thanks-
I believe the SOQL should be
I believe your original query returned no results so o was null and thus you could not dereference it to o.ChildObject__r[0]
you could also do a test for
if(o.ChildObject__r.size()>0)
All Answers
I believe the SOQL should be
I believe your original query returned no results so o was null and thus you could not dereference it to o.ChildObject__r[0]
you could also do a test for
if(o.ChildObject__r.size()>0)
Ah, didn't realize you could call the size method on the inner list like that. That did the trick - thanks!