Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Relating Records by Using an External ID
- The Account sObject has an external ID field of type text and named MyExtID
- An account record exists where MyExtID__c = ‘SAP111111’
1Opportunity newOpportunity = new Opportunity(
2 Name='OpportunityWithAccountInsert',
3 StageName='Prospecting',
4 CloseDate=Date.today().addDays(7));
5
6// Create the parent record reference.
7// An account with external ID = 'SAP111111' already exists.
8// This sObject is used only for foreign key reference
9// and doesn't contain any other fields.
10Account accountReference = new Account(
11 MyExtID__c='SAP111111');
12
13// Add the account sObject to the opportunity.
14newOpportunity.Account = accountReference;
15
16// Create the opportunity.
17Database.SaveResult results = Database.insert(newOpportunity);The previous example performs an insert operation, but you can also relate sObjects through external ID fields when performing updates or upserts. If the parent record doesn’t exist, you can create it with a separate DML statement or by using the same DML statement as shown in Creating Parent and Child Records in a Single Statement Using Foreign Keys.