Get all Parent and child objects related to the current object

I have a string which contain the name of a sobject. Now I want to get all the objects related to this object. Also want to get which kind of relationship it have with these object.

Answer

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());
}

Note: Based on your requirement just use your object API Name instead Account.

Attribution
Source : Link , Question Author : Anu , Answer Author : Ratan Paul

Leave a Comment