2

I am trying to create a Map<Id, List<sObject>> where Id = Parent Object Id and List<sObject> is a list of child objects from a specified master-detail relationship.

In SOQL, this is equivalent to:

SELECT Id, Name, (SELECT Id, Name FROM Relationship_Name__r) FROM Parent_Object_API_Name__c

I am looking for the best way in apex to do this and not via SOQL. I looked at this and this .

String relationship_name = 'Relationship_Name__r';
for(sObject item : items)
    List<sObject> children = item.getSObjects(relationship_name);

This returns a null value for children list.

for(sObject item : items)
    List<sObject> children = item.Relationship_Name__r;

This neither returns a null nor the children i.e., children.size() = 0.

I would like to specify the relationship name in a String variable (so 2nd approach above is not ideal).

Is it possible?

1 Answer 1

7

Providing the parent object and child object are both included in the query, the relationship fields are populated and can be used in Apex code.

I'm not sure what you mean by "not via SOQL". You can assign the relationship fields in Apex code but having them automatically set as a side affect of the SOQL keeps the code much simpler.

In static SOQL it would be:

Map<Id, List<SObject>> m = new Map<Id, List<SObject>>();
for (Parent_Object_API_Name__c p : [
        SELECT Id, Name, (SELECT Id, Name FROM Relationship_Name__r)
        FROM Parent_Object_API_Name__c
        ]) {
    m.put(p.Id, p.Relationship_Name__r);
}

and in dynamic SOQL it would be (using SObject.getSObjects):

String relationshipName = 'Relationship_Name__r';
String soql = ''
        + ' SELECT Id, Name, (SELECT Id, Name FROM ' + relationshipName + ')'
        + ' FROM Parent_Object_API_Name__c'
        ;
Map<Id, List<SObject>> m = new Map<Id, List<SObject>>();
for (SObject p : Database.query(soql)) {
    m.put(p.Id, p.getSObjects(relationshipName));
}

Not sure what problem you are hitting.

1
  • the getSObjects instead of the get method was what I needed. Thank you! Commented Nov 7, 2016 at 20:10

You must log in to answer this question.

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