I am trying to create a class that can dynamically execute its function independent of the sObjects and sObjectTypes provided. The class should check, wheter the sObjects provided do have existing child records of the sObjectTypes provided. So for example if I provide a list of Opportunities and the list of sObjectTypes {Activity, Attachment, OpportunityLineItem}, the class should check for every Opportunity if it has child records as defined in the sObjectType list.

The constructor for that class I have built as follows:

public DeletionChecker(list<sObject> objects, list<Schema.sObjectType> types) {...}

Now the core question is: How can I find the relation between the sObject and the list of sObjectTypes? I mean, as I don't know which sObjectTypes I will be handling, how can I know that for OpportunityLineItem the relevant field is called "OpportunityId" and for Activity the field is called "WhatId" and so on?

I hope my question is more or less clear. ;) Otherwise please ask.

1 Answer 1


You can perform Describe on sObject and call getChildRelationships() method to get all relationship name

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships(); 

Now you can getChildSObject() to get your Sobject name and can compare them and can make inner query to get all the result. You can find more information about Describe Sobject and Schema ChildRelationship

thanks @Keith_c for this.


You must log in to answer this question.

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