Search code examples
salesforceapexcustom-object

Insert to Parent and child custom object using external Id


I am trying to insert a record into a child custom object using the external id of the parent custom object. I am almost clear on how to setup the external id field in the parent object, but very confused with how to setup a foreign key in my child object. I am attaching the pics here which has details of the master and child custom objects. What I am i supposed to add to the child custom object to link its records to the parent object.

Also here is the code I got from another post in stackoverflow, but that didn't work in my case

enter image description heresumchans__City_Master__c city = new sumchans__City_Master__c(Name='[![enter image description here][1]][1]Vancouver',sumchans__PROVINCE__c = 'BC', sumchans__City_Name_Ext_Id__c = 'Vancouver');
insert city;
sumchans__City_Stat__c cityStat = new sumchans__City_Stat__c(Name = 'Vancouver', sumchans__ON_BILLINGS__c = 50, sumchans__City_Master__c=new sumchans__City_Master__c(sumchans__City_Name_Ext_Id__c='Vancouver'));
insert cityStat;

enter image description here


Solution

  • Ext. ids are meant to be used in integrations, Data Loader... They can be used in Apex too but the syntax looks bit funny. Use them in Apex if you must save on queries or want to go "dear salesforce, I don't remember if I saved this object already, I know unique identifier is 123, go figure it out yourself whether it needs insert or update".

    If you insert parent and child in same transaction - just user the Id generated into parent record. If they're separate, a while ago you did this:

    insert new sumchans__City_Master__c city = new sumchans__City_Master__c(Name=Vancouver',
        sumchans__PROVINCE__c = 'BC',
        sumchans__City_Name_Ext_Id__c = 'Vancouver'
    );
    

    Then later in another transaction you can do this without querying:

    sumchans__City_Stat__c cityStat = new sumchans__City_Stat__c(Name = 'Vancouver', 
        sumchans__ON_BILLINGS__c = 50, 
        sumchans__City_Master__r = new sumchans__City_Master__c(
             sumchans__City_Name_Ext_Id__c='Vancouver'
        )
    );
    insert cityStat;
    

    Note that I used __r instead of __c. __c would be your real foreign key, Id field, 15 or 18 characters. __r would be a reference to another object (with ext. id or query result for example), similar to writing SELECT FirstName, Email, Account.Name FROM Contact.

    In Apex it has to be as a object referece (so either query or cheat with new keyword, just to create it in memory. You won't actually save that "parent"). In things like data loader you can map values bit like myCsvExtIdColumn -> sumchans__City_Master__r.sumchans__City_Name_Ext_Id__c