Can You Set Lookup Fields with __r and External IDs?
Question
Is it possible to set a lookup field in Apex by using the relationship field (__r) and an external ID? For example, can we relate a child record to its parent by specifying the parent object with just an external ID value? If yes, how does it work, and does it apply to custom relationship fields as well?
Answer
Yes, you can set a lookup field in Apex by using the relationship (__r) field and an external ID. This is a documented Salesforce feature that allows you to relate records using external IDs instead of Salesforce record IDs. The key requirement is that the parent object must have a custom field marked as an external ID. When creating or updating a child record, you can reference the parent object with its external ID through the __r relationship field.
Here is how it works:
To relate a record to its parent using an external ID, you first create an instance of the parent object and populate only the external ID field. Then, you assign this parent object instance to the __r field of the child record. Salesforce resolves the relationship automatically during the insert or update operation.
Example 1: Standard Relationship Field
The following example demonstrates how to create an Opportunity and relate it to an existing Account using the external ID field MyExtID__c on the Account object.
Opportunity newOpportunity = new Opportunity(
Name = 'OpportunityWithAccountInsert',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(7)
);
// Create the parent record reference using the external ID.
Account accountReference = new Account(
MyExtID__c = 'SAP111111'
);
// Assign the parent object to the child record's relationship field.
newOpportunity.Account = accountReference;
// Insert the child record, automatically linking it to the parent.
Database.SaveResult result = Database.insert(newOpportunity);In this example, Salesforce automatically links the Opportunity to the correct Account record whose MyExtID__c field matches SAP111111.
Example 2: Custom Relationship Field
This feature also works with custom relationship fields. For example, consider a custom object MyObject__c with a custom lookup field Parent__c (pointing to another custom object Parent__c). The Parent__c object has an external ID field External__c.
MyObject__c newRecord = new MyObject__c(
Name = 'Test Record'
);
// Create the parent record reference using the external ID.
Parent__c parentReference = new Parent__c(
External__c = '1'
);
// Assign the parent reference to the custom relationship field.
newRecord.Parent__r = parentReference;
// Insert the child record, linking it to the parent.
insert newRecord;This demonstrates that you can use the __r field to specify the relationship for custom lookup fields as well. Salesforce resolves the relationship using the external ID specified in the parent reference.
Key Points:
- The parent object must have a custom field marked as an external ID.
- You populate only the external ID field of the parent object when setting the relationship.
- This works for both standard relationship fields (e.g.,
AccountId) and custom relationship fields (e.g.,Parent__c).
In conclusion, the use of __r fields with external IDs is a valid and powerful way to establish relationships between records in Apex. This approach simplifies operations by removing the need to query the parent record’s Salesforce ID beforehand.
Kick Start Your Career with Real-Time Project-Based Salesforce Training
Our Salesforce Course is designed to provide a comprehensive understanding of the Salesforce platform, equipping you with the key skills required to thrive in the CRM industry. The program focuses on critical modules like Salesforce Admin, Developer, and AI, combining theoretical insights with hands-on practical learning. By working on real-world projects and assignments, you’ll develop the confidence and expertise to solve complex business challenges using Salesforce solutions. Our seasoned trainers ensure you gain both technical knowledge and valuable industry insights to excel in the Salesforce ecosystem.
Beyond technical training, our Salesforce Training in New York offers customized mentoring, certification preparation, and interview guidance to enhance your career potential. With access to detailed study materials, practical project experience, and dedicated support, you’ll be fully prepared for certification exams and equipped with problem-solving abilities that employers value. Take the first step toward your Salesforce career today and unlock endless possibilities. Enroll for a Free Demo session now!

