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
Prachi SPrachi S 

Creating Parent (LIst) and Child Records (List) in a Single Statement Using Foreign Keys in Apex

Hi All,

I am trying to insert a list of related records in Apex and found the documentation that explains how to do so for inserting 1 parent and 1 child record. Here is the snippet I am talking about and link for the same:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm
public class ParentChildSample {
    public static void InsertParentChild() {
        Date dt = Date.today();
        dt = dt.addDays(7);
        Opportunity newOpportunity = new Opportunity(
            Name='OpportunityWithAccountInsert',
            StageName='Prospecting',
            CloseDate=dt);
        
        // Create the parent reference.
        // Used only for foreign key reference
        // and doesn't contain any other fields.
        Account accountReference = new Account(
            MyExtID__c='SAP111111');                
        newOpportunity.Account = accountReference;
        
        // Create the Account object to insert.
        // Same as above but has Name field.
        // Used for the insert.
        Account parentAccount = new Account(
            Name='Hallie',
            MyExtID__c='SAP111111');      
        
        // Create the account and the opportunity.
        Database.SaveResult[] results = Database.insert(new SObject[] {
            parentAccount, newOpportunity });
        
        // Check results.
        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');
            }
        }
    }
}

Now I want to replicate this functionality to insert a List of related records instead of a single record and I get an error when I just change the below line from documentation :

// Create the account and the opportunity.
Database.SaveResult[] results = Database.insert(new SObject[] { parentAccount, newOpportunity });

To:

// Create the account and the opportunity.
Database.SaveResult[] results = Database.insert(new SObject[] { parentAccountLIST, newOpportunityLIST });


Any help on what parameters change for inserting a list will be of great help.

Thank you!!


 
Best Answer chosen by Prachi S
Fabio PalladinoFabio Palladino
Hi Prachi,
I think is not possible to pass to Database.insert() statement a list of list of objects.
You can only pass a list of SObject with the same type or different type.
For example in your case you can try to write the following statement:

Database.SaveResult[] results = Database.insert(new SObject[] { parentAccount1, parentAccount2, newOpportunity1, newOpportunity2});

But this solution is static. If you want a dynaminc solution you must perform two DML statement, one on parent Object and after on child object.
You can also continue to use the technique of external id reference mentioned in your link:
 
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields.
Account accountReference = new Account(
      MyExtID__c='SAP111111');               
 newOpportunity.Account = accountReference;

regards
 

All Answers

Fabio PalladinoFabio Palladino
Hi Prachi,
I think is not possible to pass to Database.insert() statement a list of list of objects.
You can only pass a list of SObject with the same type or different type.
For example in your case you can try to write the following statement:

Database.SaveResult[] results = Database.insert(new SObject[] { parentAccount1, parentAccount2, newOpportunity1, newOpportunity2});

But this solution is static. If you want a dynaminc solution you must perform two DML statement, one on parent Object and after on child object.
You can also continue to use the technique of external id reference mentioned in your link:
 
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields.
Account accountReference = new Account(
      MyExtID__c='SAP111111');               
 newOpportunity.Account = accountReference;

regards
 
This was selected as the best answer
Prachi SPrachi S
Hi Fabio,

I had to use 2 DML statement to insert my related records and it worked just fine. 

Thank you!
Sagar Hinsu 18Sagar Hinsu 18

You can add both parent and child list to another List<SObject> and insert that list

List<SObject> sobjects = new List<SObject>();
sobjects.addAll(parents);
sobjects.addAll(childs);

Database.SaveResult[] results = Database.insert(sellingUnitsAndRelations);