+ Start a Discussion
KaityKaity 

SOQL Query

When do we use __r? 

 

Can we use __r both in Parent Object and in custom object?

 

-Kaity

Best Answer chosen by Admin (Salesforce Developers) 
TheDoctorTheDoctor
__r is used when querying through a related custom object. Here are some examples:

** StandardObject.Custom_Object__r.StandardField
** Child_Object__c.Parent_Object__r.Custom_Field__c

Hope this helps!

All Answers

TheDoctorTheDoctor
__r is used when querying through a related custom object. Here are some examples:

** StandardObject.Custom_Object__r.StandardField
** Child_Object__c.Parent_Object__r.Custom_Field__c

Hope this helps!

This was selected as the best answer
AsitM9AsitM9

We use __r for the child object query.

 

For example custom_obj__c is child of Account.:-

 

list<Account> acc=[select id,(select id  from custom_obj__r ) from Account];

 

KaityKaity

So, for any case, we can not have Account__r or Contact__r (where Account and Contact are standard object)?

 

 

deepabalisfdcdeepabalisfdc

Yes we can. Where Account is child object of any other object.
Say, you have Test__c where its child is Account object. and in SOQL you are fetching associated account's name .

So soql may be:

list<Test__c> tests=[select id,Account__r.Name from Test__c];

 



KaityKaity

Thank you everybody. I got the concept now.  :)

 

-Kaity

KaityKaity

Hi, I need your help:

 

I want to retrieve the Account Phone Number and Account Number from Contact. I've tried as below, but not getting the expected result.

 

List<Contact> conts = [SELECT ID, NAME, Account.Phone, Account.AccountNumber FROM CONTACT LIMIT 2];
System.debug('$$$$$ CONTACTS ARE @@@@@@@' + conts);

crop1645crop1645
Kaity

If you are running this in a testmethod, then org data will not be visible unless your testmethod is annoted with @isTest(seeAlldata=true)

You may also be fetching private Contacts that don't have account parents - see SFDC doc on private vs public Contacts.