function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kenji775Kenji775 

Insert with lookup using external Id failing

Hey all,
 

Working on an import project, and I am trying to create a record (Ownership__c) that has lookups to two other kinds of objects (Account, and Auto__c). Account has a field called SSN__C which is unique and set as an external ID. Auto__c has a field called VIN__c which is also unique and set as an external ID. (Keep in mind the account and auto__c will already exist in the system, I'm just creating them in my code here for clarity sake).
 

/* This chunk is just for example, in my production system the accounts and autos will already exist. Hence the reason I need to use the foreign keys */
Account newAccount = new Account(); newAccount.firstname = 'test'; newAccount.lastname = 'jones'; newAccount.SSN__c = '12345'; insert newAccount; Auto__c newAuto = new Auto__c(); newAuto.name = 'testcar'; newAuto.VIN = 'VIN9999'; insert newAuto; /* End clarity code */
Ownership__c ownership = new Ownership__c(); ownership.put('Account__c','12345'); //Lookup to Account object ownership.put('Auto__c','VIN9999'); //lookup to Auto__c objects. insert ownership;

 


The inserting the ownerhsip records fails, stating that the field is not a proper ID. I thought maybe I need to create a reference to the related objects and pass that, but that didn't work either. That attemp looked something like

 

Account thisAccount = new Account(SSN__c='121212');
Auto__c thisAuto = new Auto__c(VIN__c='VIN1234');

Ownership__c ownership = new Ownership__c();
ownership.put('SSN__c',thisAccount.id);
ownership.put('VIN__c',thisAuto.id); 
insert ownership;  

 but that doesn't work either, because of course the two created objects don't have ID's yet. I tried passing the objects to the __r version of the relationship fields, but that doesn't work either. 


I thought I could set the value of the lookup to an external ID and it would work. Am I mistaken? What am I doing wrong here? 

Kenji775Kenji775

Woot, I got it. It goes like this

Account thisAccount = new Account(SSN__c='121212');
Auto__c thisAuto = new Auto__c(VIN__c='VIN1234');

Ownership__c ownership = new Ownership__c(SSN__r=thisAccount,VIN__r=thisAuto);

insert ownership;  

 

 You pass the object as a reference during creation of the object. Doesn't seem like you can set it after creation.