Solution : By iterating through all the fields of an object and checking if it has any reference,we can fetch all the parent objects associated to an object.
In this example,we fetch all the parent objects associated to opportunity object.
Sample Apex Code:
Set<String> lstObject = new Set<String>();
for(Schema.SobjectField sField: opportunity.SobjectType.getDescribe().fields.getMap().Values()) {
if(sField.getDescribe().getType() == Schema.DisplayType.REFERENCE) {
for(Schema.sObjectType sObj : sField.getDescribe().getReferenceTo()) {
lstObject.add(string.valueOf(sObj));
}
}
}
system.debug('Parent Objects associated with Opportunity:'+lstObject);
Output: When we run the above code in workbench,output will be like this:
In this example,we fetch all the parent objects associated to opportunity object.
Sample Apex Code:
Set<String> lstObject = new Set<String>();
for(Schema.SobjectField sField: opportunity.SobjectType.getDescribe().fields.getMap().Values()) {
if(sField.getDescribe().getType() == Schema.DisplayType.REFERENCE) {
for(Schema.sObjectType sObj : sField.getDescribe().getReferenceTo()) {
lstObject.add(string.valueOf(sObj));
}
}
}
system.debug('Parent Objects associated with Opportunity:'+lstObject);
Output: When we run the above code in workbench,output will be like this:
No comments:
Post a Comment