function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
3 Creeks3 Creeks 

Dynamically finding all sObjects that have child relationships with another sObject

Hi -

I am wondering what the best practices are when trying to determine all objects that reference another object, including those objects that are reference it generically.   My scenario is that I am trying to determine all objects, whether standard or custom, that have a child relationship with the Case object. I have a method that does a getGlobalDescribe() to retrieve all sObjects and then loops through them to determine which objects have a childRelationship with Case.  Here is the method:
 
public static Map<String, String> getCaseRelationships() {
		Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
		Schema.SObjectType c = Case.sObjectType;	
		Map<String, String> rObjs = new Map<String, String>();
		
		for (String s : gd.keySet()) {
			if ( gd.get(s).getDescribe().isAccessible() && gd.get(s).getDescribe().isQueryable() && !gd.get(s).getDescribe().isDeprecatedAndHidden() ) {
				for (Schema.ChildRelationship sC : gd.get(s).getDescribe().getChildRelationships()) {
					if (sC.getChildSObject() == c) {
						rObjs.put( String.valueOf(sC.getField()), String.valueOf(gd.get(s).getDescribe().getLocalName()) );
					}
				}
			}			
		}
		return 	rObjs;
	}


Works fine except for sObjects like RecordType.   If there are case record types, RecordTypeId, shows up on the case object with Type = "Reference", but will not be returned as an object with a child relationship to case by getChildRelationship().  I assume this is because RecordType is used to hold the record type references for all sObjects, so instead of having a CaseId field, it has a sObjectType field that indicates if the recordType is associated with Case.

My question is, what is the best practices for dynamically finding ALL sObject that have child relationships with Case, including those like RecordType?

Thanks
 
KevinPKevinP
Your code above will help you identify record-level relationships. (ie, this record is related to another record) however, indirect object level relationships, (ie: meta data relationships like record type) to my knowledge, have to be discovered the hard way. Thankfully, I don't think there are many of them. Record Type is about the only one I can think of.