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

  • 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');
                }
            }