3

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

1
  • referencing your comment to Adrian below, that problem is a bit simpler as lookup relationships can simply be reparented (you did say move, not copy) and some master-detail relationships allow for reparenting as well (it is a config option in the point and click definition)
    – cropredy
    Commented Aug 9, 2016 at 1:36

1 Answer 1

4

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';
1
  • I'm a little confused on how I should approach this issue, but what I want to do is move related lists from source opportunity to target. What I'm thinking is to get all child objects, find out which ones actually are being used, and then from there only move those related lists to the target opportunity. What do you think of this approach? Commented Aug 9, 2016 at 0:49

You must log in to answer this question.

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