Skip to Content

TheBlogReaders.com

Salesforce.com, PHP, MySQL, Javascript, Ajax, Htacces

How to insert Parent and Child records in a Single DML Statement?

SFDC-DeveloperIt can be done with help of External Id.
Use a 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.Inserting Standard objects (Parent and Child) records in a Single DML Statement:

Contact con = new Contact(lastName='TheBlogReaders');
con.Email = 'info@theblogreaders.com';
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields. so create a AccountRef__c as a custom field with External Id Options.
Account accReference = new Account(AccountRef__c='123456789');
con.Account = accReference;
// Create the Account object to insert.
// Same as above but has Name and necessary mandatory fields for inserting the parent record.
Account acc = new Account(Name='Hallie', AccountRef__c='123456789');
// Create the Account and the Contact in single statement using database.insert or insert DML.
Database.SaveResult[] results = Database.insert(new SObject[] {acc, con});
// 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');
}
}

Inserting Custom objects (Parent and Child) records in a Single DML Statement:
here assume Parent__c and Child__c is a custom objects:
create a External Id in Parent__c object called Parent_Ref__c.

Child__c c = new Child__c();
c.Name = 'ChildRecord1';
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields. so create a Parent_Ref__c as a custom field with External Id Options.
Parent__c parentReference = new Parent__c(p.Parent_Ref__c = 'abc1234');
c.Parent__r = parentReference;   //here make sure the field should be relations (__r) field (i.e Parent__r)
// Create the Parent__c object to insert.
// Same as above but has Name and necessary mandatory fields for inserting the parent record.
Parent__c p = new Parent__c();
Name ='TheBlogReaders';
p.Parent_Ref__c = 'abc1234';
// Create the Parent__c and the Child__c in single statement using database.insert or insert DML.
Database.SaveResult[] results = Database.insert(new SObject[] { p, c });
// 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');
}
}

(1326)

Previous
Next

Leave a Reply