To relate a record to its parent record with an external ID, the parent object must have a custom field marked as External ID. Create the parent sObject with an external ID value, and then set this record as a nested sObject on the record you want to link.
This example shows how to relate a new opportunity to an existing account. The account has an external ID field, named MyExtID, of type text. Before the new opportunity is inserted, the Account record is added to this opportunity as a nested sObject through the Opportunity.Account relationship field. The Account sObject contains only the external ID field.
Opportunity newOpportunity = new Opportunity( Name='OpportunityWithAccountInsert', StageName='Prospecting', CloseDate=Date.today().addDays(7)); // Create the parent record reference. // An account with this external ID value already exists. // This sObject is used only for foreign key reference // and doesn't contain any other fields. Account accountReference = new Account( MyExtID__c='SAP111111'); // Add the nested account sObject to the opportunity. newOpportunity.Account = accountReference; // Create the opportunity. Database.SaveResult results = Database.insert(newOpportunity);
The previous sample 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.