Get all Parent and child objects related to the current object

Many times you have to find the related objects either you do it the hardcode way or another. Here I am sharing an example of how you can dynamically get the Related either Parent or Child.

The below examples are for the standard “Account” object. However, this will work for any other standard or custom object – don’t forget to add __c for the custom objects.

Get All Parent objects.

for(Schema.SobjectField strFld: Account.SobjectType.getDescribe().fields.getMap().Values())
{
    if(strFld.getDescribe().getType() == Schema.DisplayType.REFERENCE)
    {
        system.debug('==parent object='+strFld.getDescribe().getReferenceTo());
    } 
}

Get All Child objects.

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: R.getChildRelationships()) 
{
  system.debug('====child object==='+cr.getChildSObject());
}

Getting Relationship Names

Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship cr: R.getChildRelationships()) 
{
  system.debug('====child object relation Name==='+cr.getRelationshipName());
}

Source: https://salesforce.stackexchange.com/questions/117050/get-all-parent-and-child-objects-related-to-the-current-object
Credit: https://salesforce.stackexchange.com/users/18731/ratan-paul

Leave a Comment