Hi I have a base object that is a main object and I do have some other objects which is coming dynamically. I need to find out the relationship between the objects in apex class. If there any way to find the relationship between two object and get the field through which it is related. Please do help me out how can I get the solution for this issue.
2 Answers
If you would like to accomplish this programmatically, you could inspect the describe information in order to find a lookup field which points to the main object. This would roughly look like the following snippet:
Schema.sObjectType parentType = MainObject__c.sObjectType;
List<Schema.SObjectField> fieldList = obj.getDescribe().fields.getMap().values();
for (Schema.SObjectField field : fieldList) {
Schema.DescribeFieldResult fieldDesc = field.getDescribe();
if (Schema.DisplayType.ID == fieldDesc.getType() &&
new Set<Schema.sObjectType>(fieldDesc.getReferenceTo()).contains(parentType)) {
System.debug('Found valid relationship with main object');
}
}