1

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 2

5

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');
    }
}
-1

You can use the Schema Builder to accomplish this.

1
  • I need to do it through my apex class. That is dynamically.
    – Anu
    Commented Oct 2, 2014 at 9:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .