You need to sign in to do that
Don't have an account?
How to get a subquery field value using Dynamic Apex?
Hi,
I need to get a Field value from a Dynamic Query and I can do it when the query is over a child-to-parent relationship like this:
Object FieldValue;
SObject c = Database.query('select id, FirstName, AccountId, Account.Name from Contact limit 1');
SObject a = c.getSObject('Account');
FieldValue= a.get('Name');
But, when I try to get the value from a parent-to-child relationship I get the error message "System.SObjectException: Invalid relationship Contacts for Account".
Here is the example of the code I used:
Object FieldValue;
SObject a = Database.query('SELECT id, (SELECT Name FROM Contacts limit 1) FROM Account limit 2');
SObject c = a.getSObject('Contacts');
FieldValue = c.get('Name');
The query is working fine and by the other way, I already know the subquery in normal (not dynamic) Apex is retrieved as an Object array. But, how could I get the child field value from this query? (In this case, How could I get the list of Names of the related Contacts from the retrieved Accounts?).
The program is being stopped at line ("SObject c = a.getSObject('Contacts')" ). I looked into the apex documentation but I couldn't find such an example to follow. Please at least let me know if this is possible.
Regards,
Wilmer
SObject[] a = Database.query('SELECT id, (SELECT Name FROM Contacts limit 1) FROM Account limit 2'); SObject[] c = a.get(0).getSObjects('Contacts'); FieldValue = c.get(0).get('Name');
This works ok for me. I've hardcoded the first item in each list - just loop around the collection otherwise. Running it in a controller in a VF page.
R.
All Answers
SObject[] a = Database.query('SELECT id, (SELECT Name FROM Contacts limit 1) FROM Account limit 2'); SObject[] c = a.get(0).getSObjects('Contacts'); FieldValue = c.get(0).get('Name');
This works ok for me. I've hardcoded the first item in each list - just loop around the collection otherwise. Running it in a controller in a VF page.
R.
I have no idea because I've never tried to do that, but I can say that this line is clearly wrong:
Because that subquery, if it worked, will return a list of sObjects, not a single sObject. As such, you might try getSObjects (plural) on it instead.
Hi Richie D,
Thank you very much for your appropiate answer. It is now working!
Regards,
Wilmer
Hi werewolf.
Thanks you very much for your answer.
Regards,
Wilmer