2

Have a junction object that is a many to many relationship between two obejcts - Account and Publisher. As mentioned in the documentation I set the key in the Is there an easy way to upsert junction records without creating duplicates. Below is my code. How do I specify an upsert if Account__c and Publisher__c are the same. Do I need to check for existing records via a select before inserting? Is there a way to make the platform aware that Account__c Publisher__c is unique for the set.

list<AccountPublisherAssociation__c> lstAssociations = new list<AccountPublisherAssociation__c>();

    for(string sPublisherId : lstOfPublisherIds){
        AccountPublisherAssociation__c accPublisherJunction = new AccountPublisherAssociation__c();            
    accPublisherJunction.Account__c = ParentId;
    accPublisherJunction.Publisher__c = sPublisherId;                       
        lstAssociations.add(accPublisherJunction);
    }

    upsert lstAssociations;

1 Answer 1

3

One possible way is to have an external ID on the junction object which would be a concatenation of Account and Publisher ids.

Upserting Records

To determine whether a record already exists, the upsert statement or Database method uses the record’s ID as the key to match records, a custom external ID field, or a standard field with the idLookup attribute set to true.

Then when creating a record for AccountPublisherAssociation__c calculate its value and assign to the record:

for(string sPublisherId : lstOfPublisherIds)
{
    AccountPublisherAssociation__c accPublisherJunction = new  AccountPublisherAssociation__c();            
    accPublisherJunction.Account__c = ParentId;
    accPublisherJunction.Publisher__c = sPublisherId;
    accPublisherJunction.Key__c = ParentId + '' + sPublisherId; //this is your External Id

    lstAssociations.add(accPublisherJunction);
}

upsert lstAssociations Key__c;

That will prevent from duplicates. Also check out this article for more details - Import related records using an External ID

2
  • How can I set up an external ID field in salesforce lightning on a custom object. I do not see the options there.
    – user275157
    Aug 12, 2018 at 6:47
  • You should create a custom text field and make it External Id. Go to Object Manager in Setup, find your object there, then find the Fields section and click New to create a custom field
    – Eduard
    Aug 12, 2018 at 8:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .