Activity Forums Salesforce® Discussions Is it possible to insert a Salesforce Parent-Child record in one DML operation?

  • PRANAV

    Member
    March 23, 2018 at 1:42 pm

    Hi Kapil,

    You can use Database.SaveResult[] results = Database.insert(new SObject[] {acc, con});

    For more you can refer to the "Creating Parent and Child Records in a Single Statement Using Foreign Keys" standard salesforce document.

    Hope this helps you.

  • Archit

    Member
    March 26, 2018 at 8:03 am

    Hello Kapil,

    I was searching out an answer of your question and I found something related that may be it would be helpful to get your answer. Below is the piece of code which you need to run in anonymous window It creates 2 Account records and 2 Child opportunity records referring to same parent account. And you will get Ids of all inserted records in debug.

     

    Date dt = Date.today();
    dt = dt.addDays(7);
    
    List lstSobject = new List();
    
    Opportunity newOpportunity1 = new Opportunity(Name='OpportunityWithAccountInsert1',StageName='Prospecting',CloseDate=dt);        
    Account accountReference = new Account(MyExtID__c='12345'); 
    newOpportunity1.Account = accountReference;
    lstSobject.add(newOpportunity1);
    
    Opportunity newOpportunity2 = new Opportunity(Name='OpportunityWithAccountInsert2',StageName='Prospecting',CloseDate=dt);        
    Account accountReference = new Account(MyExtID__c='12345'); 
    newOpportunity2.Account = accountReference;
    lstSobject.add(newOpportunity2);
    
    Account parentAccount1 = new Account(Name='Hallie',MyExtID__c='SAP1111112'); 
    lstSobject.add(parentAccount1);
    Account parentAccount2 = new Account(Name='Hallie',MyExtID__c='SAP111111'); 
    lstSobject.add(parentAccount2);
    
    Database.SaveResult[] results = Database.insert(lstSobject);
    
    for (Integer i = 0; i < results.size(); i++) {
                if (results[i].isSuccess()) {
                System.debug('Successfully created ID: '
                      + results[i].getId());
                } else {
                System.debug('Error: could not create sobject '
                      + 'for array element ' + i + '.');
                System.debug('   The error reported was: '
                      + results[i].getErrors()[0].getMessage() + '\n');
                }
            }
    
  • Parul

    Member
    September 18, 2018 at 7:40 pm

    Here I am adding code snippet:

    public class ParentChildSample {
    public static void InsertParentChild() {
    Date dt = Date.today();
    dt = dt.addDays(7);
    List<Opportunity> opp = new List<Opportunity>();
    List<Account> acc = new List<Account>();

    for(Integer i = 0; i < 3; i++){

    Opportunity newOpportunity = new Opportunity(Name='OpportunityWithAccountInsert ' +i,StageName='Prospecting',CloseDate=dt);
    Account accountReference = new Account(MyExtID__c='SAP111111'+i);
    newOpportunity.Account = accountReference;
    Account parentAccount = new Account(Name='Hallie '+i);
    system.debug('DDDDDDDDDDDDDDDDDD'+newOpportunity.Account);
    opp.add(newOpportunity);
    acc.add(parentAccount);

    }

    Database.SaveResult[] results = Database.insert(acc,opp);

    for (Integer i = 0; i < results.size(); i++) {
    if (results[i].isSuccess()) {
    System.debug('Successfully created ID: '+ results[i].getId());
    } else {
    System.debug('Error: could not create sobject '+ 'for array element ' + i + '.');
    System.debug(' The error reported was: '+ results[i].getErrors()[0].getMessage() + '\n');
    }
    }
    }
    }

     

    Thanks

  • shariq

    Member
    September 19, 2018 at 9:01 pm

    Hi,

    You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of creating the parent record first, querying its ID, and then creating the child record. To do this:Create the child sObject and populate its required fields, and optionally other fields.
    Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only the external ID field defined and no other fields set.
    Set the foreign key field of the child sObject to the parent reference sObject you just created.
    Create another parent sObject to be passed to the insert statement. This sObject must have the required fields (and optionally other fields) set in addition to the external ID field.
    Call insert by passing it an array of sObjects to create. The parent sObject must precede the child sObject in the array, that is, the array index of the parent must be lower than the child’s index.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs