4

I by no means consider myself well versed in Apex code but while trying to understand what this Apex class is doing, I couldn't wrap my head around what is happening in this block of code. I am hoping someone can clarify what I am misunderstanding.

if (interaction.Opportunity__r != null) {
 interaction.Opportunity__c = interaction.Opportunity__r.Id;
 interaction.Opportunity__r = null; 
}

For starters, my understanding is '__r' and '__c' are different representations of the same relationship. In formula fields, trying to return Opportunity__r without appending a field would flag as a syntax error (because it does not return a value). So I read this and understand it was saying "X = X"; My understanding is there is no Opportunity__r without a value already being in Opportunity__c while the last line "__r = null" does nothing since "__r" does not represent a value. Please clarify if this code is doing something that I am not understanding.

6

The __c suffix represents the actual Id value stored in the database. The __r suffix represents the entire parent object. If you are trying to save a record to the database and you specify both, you can cause errors, which is typically why you would see this type of code. It basically says, if there is a parent record in memory, clear it out and just store the Id.

See also: What are the object and field name suffixes that Salesforce uses? Such as __c and __x

6
  • 1
    Not always a parent object. Could simply be a related object. – Phil W Jan 8 '20 at 21:21
  • 1
    I am responding to this person's question about this code. – Adrian Larson Jan 8 '20 at 21:21
  • OK, though the way you phrased it, it appears to be generic (since you only provide the suffix detail). – Phil W Jan 8 '20 at 21:24
  • I understand the difference between __r and __c as far as what they are, but what I don't understand is how there can be an __r when there isn't an __c ; doesn't the relationship start at __c? – Jaron Jan 8 '20 at 21:29
  • 1
    When you use field paths in an SOQL query, like "SELECT Opportunity__r.Id ...", you find that the returned object includes the related object and any of its explicitly queried fields. This is literally another in-memory SObject (here an Opportunity) and the __r field contains the reference to that object allowing you to traverse to it using the field path dot notation. The code ensures that just that related object's ID is retained, in the lookup field, and the referenced Opportunity instance is detached, in memory (not in the database), from the interaction for the reasons covered by Adrian. – Phil W Jan 8 '20 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.