function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ariane Gardou 3Ariane Gardou 3 

How to find an object without parent object in apex ?

Hello,
I am actually writing a code that helps to get automatically the dependencies between Object.
While writing my code, I faced an issue. I cannot find a way to know when an object doesn't have a parent object.
How can I find that in apex ?
Best Answer chosen by Ariane Gardou 3
chanchal_:)chanchal_:)
Schema.DescribeSObjectResult STApiName = Student__c.sObjectType.getDescribe();
        List<String> ListStudentApiNames =  new list<String>();
        for(string apiName : STApiName.fields.getMap().keySet()){
            ListStudentApiNames.add(apiName);
        }

Schema.DescribeFieldResult StField;
Schema.DisplayType StFieldType;
 for(string sApiName : ListStudentApiNames){

 StField = Schema.getGlobalDescribe().get('Student__c').getDescribe().
                    fields.getMap().get(sApiName).getDescribe();
 StFieldType = StField.getType();
if(String.valueOf(SliFieldType) == 'REFERENCE'){  
//This Object has a parent record.
}

}

If you want to check if a particular object has any parent object whether it's lookup type or master-detail. It'll help.   

All Answers

Sharat C 2Sharat C 2
Just a guess can't you use schema methods to pull all fields and identify based on feild type ? 
harsha__charsha__c
Can you describe more about what does "dependencies between objects means"?

Are you trying to check if the 2 given objects have any relationship between them? If so, you have to get the child relationships of both the objects (using schema methods) and check if the other one is present in the child relationships of one.

-Harsha
chanchal_:)chanchal_:)
Schema.DescribeSObjectResult STApiName = Student__c.sObjectType.getDescribe();
        List<String> ListStudentApiNames =  new list<String>();
        for(string apiName : STApiName.fields.getMap().keySet()){
            ListStudentApiNames.add(apiName);
        }

Schema.DescribeFieldResult StField;
Schema.DisplayType StFieldType;
 for(string sApiName : ListStudentApiNames){

 StField = Schema.getGlobalDescribe().get('Student__c').getDescribe().
                    fields.getMap().get(sApiName).getDescribe();
 StFieldType = StField.getType();
if(String.valueOf(SliFieldType) == 'REFERENCE'){  
//This Object has a parent record.
}

}

If you want to check if a particular object has any parent object whether it's lookup type or master-detail. It'll help.   
This was selected as the best answer