[SalesForce] Get all child objects of a parent

I want to get all child objects of a parent object and store them in a list. I've been trying to find out how to do so but haven't found much help. I know we have to use a SOQL query but can't figure out how to format it so I get all child objects from the parent.

For ex, if the parent is Opportunity, then I'm trying to get all child objects of Opportunity which could be products, contacts, etc etc

Best Answer

If you want all the child metadata, you can loop through the getChildRelationships results like so:

for (ChildRelationship relation : SObjectType.Opportunity.getChildRelationships())
{
    String relationshipName = relation.getRelationshipName();
    // the above value is what you would use in a SOQL sub-query
    // e.g. SELECT Id, (SELECT Id FROM Children) FROM MyObject

    SObjectType childType = relation.getChildSObject();
    // the above value is the token for the child object

    SObjectField lookupField = relation.getField();
    // the above value is the token for the lookup field on the child object
}

If you want to get the child data, you'll need to build a dynamic query using the above results from the getRelationshipName method.

Building dynamic queries in an elegant way is perhaps beyond the scope of this question. Below is a simple example of what it might look like.

List<String> subqueries = new List<String>();
for (ChildRelationship relation : SObjectType.Opportunity.getChildRelationships())
    subqueries.add('(SELECT Id FROM ' + relation.getRelationshipName() + ')');
String query = 'SELECT ' + String.join(subQueries, ',') + ' FROM Opportunity';
Related Topic