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
Sindhu AmbarkarSindhu Ambarkar 

Nested soql query from grandparent

Hi,
I need to fetch the records from grantparent-parent-child
Please help me.
Thanks & Regards,
Sindhu Ambarkar.
JyothsnaJyothsna (Salesforce Developers) 
Hi Sindhu,

Please check the below sample code.

VisualForce Page:
<apex:page controller="LookupHierarchy">
  <apex:form >
  <apex:pageBlock >
  <apex:pageBlockTable value="{!parent}" var="p">
  <apex:column headerValue="Parent name" value="{!p.name}"/>
  <apex:column >
  <apex:pageBlockTable value="{!p.childs__r}" var="c">
  <apex:column value="{!c.name}"  headerValue="Child Names"/>
  <apex:column >
  <apex:pageBlockTable value="{!Grand}" var="gc">
  <apex:column value="{!gc.name}"   rendered="{!if(c.name==gc.Child__r.name,'true','false')}" />
  <apex:column >
  <apex:pageBlockTable value="{!supergrand}" var="sgc">
  <apex:column value="{!sgc.name}" headerValue="Super grandChild" rendered="{!if(gc.name==sgc.GrandChild__r.name,'true',false)}"/>
  </apex:pageBlockTable>
     
   </apex:column>
  
  </apex:pageBlockTable>
  </apex:column>
  </apex:pageBlockTable>
  </apex:column>
  </apex:pageBlockTable>
  </apex:pageBlock>
  </apex:form>
  
</apex:page>

Controller:
 
public with sharing class LookupHierarchy {

    public List<SuperGrandChild__c> supergrand { get; set; }

    public List<GrandChild__c> Grand { get; set; }

    public List<child__c> child { get; set; }

    public List<parent__c> parent { get; set; }
    public LookupHierarchy (){
       parent =new List<parent__c>();
       parent=[select name,(select name from Childs__r) from parent__c];
       Grand =[select name,child__r.name from GrandChild__c];
       supergrand =[select name,GrandChild__r.name from SuperGrandChild__c];
       
    }
}

Screenshot:

User-added image


Hope this helps you!
Best Regards,
Jyothsna
Sindhu AmbarkarSindhu Ambarkar
Hi Jyotsna,

I need to fetch the records from grandprent using single soql query.
Thanks & Regards,
Sindhu Ambarkar.