+ Start a Discussion
MammuMammu 

Custom Object relationship query?

[SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : acctIds] In this query we will retrieve Contacts based on Account IDs,  I want to implement the same functinality using Custom Object  Where Parent object is Campsite__c and Child Object is Campsite_Reservation__c. Can any body write the query? And anyone explain when to use __r and  __c
SaranSaran
HI,

Create a set that saves all your parent object id. i.e parentObjectIdSet.

The use the following query,

if the parent field name on child object is Campsite__c then,

[select id, name, field1__c from Campsite_Reservation__c where Campsite__c in: parentObjectIdSet];

This is to retrive particular child records.
Nitin PaliwalNitin Paliwal
HI Mammu,
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    ]
                     ,or
                    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 ){
                     campSiteReservations.addAll(tempObj.Campsite_Reservation__r);
                   }

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.

Thanks