+ Start a Discussion
naveen kunurunaveen kunuru 

relationship soql

hello lads how to  write a custome child to parent soql?
and custome parent to child soql? thanks
PratikPratik (Salesforce Developers) 
Hi Naveen,

The best article to understand it:

Hello Naveen,

 This Link explains relationship queries in a simple way. -- 

Thanks !!
Nitin PaliwalNitin Paliwal
Hi Naveen,
To accomplish your requirement, there are two Methods for writing the SOQL :

Method 1 -  Child-to-parent relationship, we can use dot notation to access the parent object fields
                    In this method your query would be like this,
                    list<Campsite_Reservation__c> campSiteReservations  =   [SELECT Id,field_Name__c,Campsite__r.field1__c  from Campsite_Reservation__c where     Campsite__c  In :campSiteIds    ]
                    list<Campsite_Reservation__c> campSiteReservations  = [SELECT Id,field_Name__c,Campsite__r.field1__c  from Campsite_Reservation__c WHERE Campsite__r.Id In :campSiteIds]

Method 2 - Parent-to-child relationship queries do not use dot notation
                   list<Campsite__c> campSites = [SELECT Id,field1__c,(SELECT Id,field_Name__c FROM Campsite_Reservation__r) FROM Campsite__c In :campSiteIds];
                   list<Campsite_Reservation__r> campSiteReservations = new list<Campsite_Reservation__r>();
                  for(Campsite__c tempObj : campSites ){

Now, the use of "__r" and "__c":
As can be seen from the Method 1, "__r" is used when we need to access the fields of the parent object in the Child-to-parent relationship SOQL, like "Campsite__r.Id " in your case.
As from the Method 2, "__r" is also used in case when getting the child records using inner query.
NOTE : in method 2, "__r" is not used with the fields of the child object and parent object.

I think this clarified your questions.
Please go through this link http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_relationships_and_custom_objects.htm#sforce_api_calls_soql_relationships_and_custom_objects
for more understanding.