We can use recursion in apex to find a self-lookup hierarchy in a custom object.
Object:
Custom_Object__c
Field:
Parent__c (This is a lookup to itself i.e Custom_Object__c)
Now, we will try to go inside the n-level deep hierarchy with the help of recursion in the apex.
@AuraEnabled
public static List<Custom_Object__c> retrieveHierarchyRecords(String param1, String param2){
try {
if(String.isBlank(param1)) return null;
if(String.isBlank(param2)) return null;
List<Custom_Object__c> parents = [SELECT Id, Field1__c, Field2__c, Field3__c, Field4__c, Parent__c FROM Custom_Object__c WHERE Field1__c =: param1 AND Field2__c =: param2];
if(parents == null) return null;
if(parents.size() == 0) return null;
List<String> ids = new List<String>();
List<Custom_Object__c> res = new List<Custom_Object__c>();
for(Custom_Object__c p : parents){
ids.add(p.Id);
res.add(p);
}
List<Custom_Object__c> result = findChildren(ids,res);
return result;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
public static List<Custom_Object__c> findChildren(List<String> ids,List<Custom_Object__c> res){
if(ids == null) return res;
List<String> idList = new List<String>();
List<Custom_Object__c> result = [SELECT Id, Field1__c, Field2__c, Field3__c, Field4__c, Parent__c FROM Custom_Object__c WHERE Parent__c IN : ids];
for(Custom_Object__c a: result){
res.add(a);
if(String.isBlank(a.Field1__c)){
idList.add(a.Id);
}
}
if(idList == null) return res;
if(idList.size() == 0) return res;
return findChildren(idList,res);
}
In the above example, we are searching for the hierarchy of Custom_Object__c where if Field1__c is empty, then only it would have further children and we have Parent__c which defines the parent lookup id.
This example shows only the retrieval of records, but following this method, we can do much more, such as DML operations also.
Get certification for your knowledge in the fundamentals of Computer functioning by clearing the Computer Certification exam conducted by StudySection. After going through this Computer Certification exam, you will be able to evaluate your basic knowledge of computers