[SalesForce] updating the child record and linking it to parent

I have scnerio where I am loading the child record from an external system and I want to connect it with the parent record. But I do not have the sfdc id
of the parent record that I can put in the lookup field.

On doing some research I found that we can use external id of the parent to connect both child and parent record but I am not clear how this relation can be established with the external id?

Best Answer

The External Id needs to be on the record in Salesforce.

Say you have:

Account -> (Name = 'Example Account', External_Id__c = 'ABCD');

To link the Child Lookup using the External Id you would do:

Contact c = New Contact(LastName = 'Test', Account = New Account(External_Id__c = 'ABCD'));
upsert c;

Note For custom object you need to use the relationship so if the Lookup is The_Parent__c you would use The_Parent__r = New The_Parent__c(External_Id__c = 'ABCD')

Note The external Id operation requires you to use upsert.

If you simply want to update the Account itself:

Account a = New Account(External_Id__c = 'ABCD', Name = 'UpdatedName');
database.upsert(a, Account.External_Id__c);

or

upsert a External_Id__c

To upsert the record itself you would specify the external Id field and populate it

Related Topic