What’s the difference between __c and __r ?

 


What’s the difference between __c and __r ?


'__c' is used for Custom Objects.
For example: CustomObject__c
It is used to reference custom object in Apex, formula field etc.

'__r' is for Custom Objects Reference 
For example: CustomObject__r
It is used to reference custom object relationship name in Apex,formula field etc.


Some details -

'__r' represents custom relationship.
There are two uses for __r. 
We use it when we query a custom relationship from child to parent, or from parent to child.

For example, if we have two custom objects, called Quote__c and QuoteLine__c, where the QuoteLine has a field that references a Quote as its parent then we can query from child to parent, or parent to child.

The child to parent relationship query -

SELECT Id, Quote__c, Quote__r.Number FROM QuoteLine__c

The parent to child relationship query -

SELECT Id, Name, (SELECT Id, Name FROM QuoteLine__r) FROM Quote__c


To access parent and child records in Apex Code, we will use the same syntax-

QuoteLine__c child = [select id,a__c,b__c .. from QuoteLine__c where ..<filter condition>];
if(child.Quote__r.name == 'Master') {
    // Some Work
}

Quote__c parent = [select id,a__c,b__c .... from Quote__c where ..<filter condition>];
for(QuoteLine__c child:parent.QuoteLines__r) {
    // Some Work
}

Each of these serve a specific purpose depending on our intent.



Reference(s) - 

https://developer.salesforce.com etc


Comments