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
Anjali Sharma 87Anjali Sharma 87 

Realationship Query on page

Hi 

How to write the relationship query and how to fetch the record from the query on visaulforce page
For ex i have one account object and one contact obj then how to write the relationship from parent to child and child to parent bcoz when i am using the query it will give only id 
Account con;
con = [select account.name,(Select contact.firstName,contact.lastName from account.contacts) from account limit 1];
system.debug(con);

how to fetch the value of contact.last name and same when i use child to parent ?????
And then how to to display it on visualforce page.

Please explain me!!!
Best Answer chosen by Anjali Sharma 87
KaranrajKaranraj
You have to do using nested <apex:repeat> tag to get the child query data. Check the below code for the sample

Apex Controller
public with sharing class AccountChild {

public List<Account> Accounts {get;set;}
 public AccountChild (){
    Accounts = [ Select id,Name,(select FirstName,lastName from contacts) from Account];
   //your other logic
  }
}
Visualforce Page:
 
<apex:page controller="AccountChild" >
  
  <apex:repeat value="{!Accounts}" var="acc">
   <h1> Account Name : <apex:outputText value="{!acc.Name}" /> </h1>
    <apex:repeat value="{!acc.Contacts}" var="con">
     Contact First Name : {!con.FirstName} <br/>
     Contact Last Name : {!con.LastName} <br/> <br/>
    </apex:repeat>
  
  </apex:repeat>
</apex:page>


 

All Answers

KaranrajKaranraj
You have to do using nested <apex:repeat> tag to get the child query data. Check the below code for the sample

Apex Controller
public with sharing class AccountChild {

public List<Account> Accounts {get;set;}
 public AccountChild (){
    Accounts = [ Select id,Name,(select FirstName,lastName from contacts) from Account];
   //your other logic
  }
}
Visualforce Page:
 
<apex:page controller="AccountChild" >
  
  <apex:repeat value="{!Accounts}" var="acc">
   <h1> Account Name : <apex:outputText value="{!acc.Name}" /> </h1>
    <apex:repeat value="{!acc.Contacts}" var="con">
     Contact First Name : {!con.FirstName} <br/>
     Contact Last Name : {!con.LastName} <br/> <br/>
    </apex:repeat>
  
  </apex:repeat>
</apex:page>


 
This was selected as the best answer
Anjali Sharma 87Anjali Sharma 87
Thanks karanraj it is working bt actually i m facing the problem in custom objects for example suppose we have one Master custom object Store__c and child objects Booktest__c and then what is query ???? i m writing 
List<Store__c> stlst ;
stlst = [Select Store_name__c,Store_num__c ,(Select Book_name__c,quntiy__c,Store__c from Books__r) from Store__c];
Books__r is the relationship name and store_name_c, store_num_c are master obj fileds and rest three belongs to child obj i.e store_c 

Please help me!!!!