Activity › Forums › Salesforce® Discussions › Can we insert parent and child object record in single DML statement?
Tagged: Account, Contact, Database, DML Statement, External ID, Parent Child Object
-
Can we insert parent and child object record in single DML statement?
Posted by Himanshu on April 14, 2016 at 7:33 AMCan we insert parent and child object record in single DML statement?
Avnish Yadav replied 7 years, 8 months ago 4 Members · 3 Replies -
3 Replies
-
Try something like below: Note that reference field must be external id field on parent object. Here i have used SLASerialNumber__c as external id field.
Contact con = new Contact(lastName=’bhardwaj’);
con.Email = ‘naman.bhardwaj@test.com’;Account accRef = new Account(SLASerialNumber__c=’12’);
con.Account = accRef;Account acc = new Account(Name=’namanTestAcc’, SLASerialNumber__c=’12’);
Database.SaveResult[] results = Database.insert(new SObject[] {acc, con});
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug(‘Successfully Created ID: ‘+ results[i].getId());
}
} - [adinserter block='9']
-
To insert the parent-child object record in single DML statement as follows:
Inserting Custom objects (Parent and Child) records in a Single DML Statement:
here assume Parent__c and Child__c is a custom object:
create a External Id in Parent__c object called Parent_Ref__c.Child__c c = new Child__c();
c.Name = ‘ChildRecord1’;
Parent__c parentReference = new Parent__c(p.Parent_Ref__c = ‘abc1234′);
c.Parent__r = parentReference;
Parent__c p = new Parent__c();
Name =’TheBlogReaders’;
p.Parent_Ref__c = ‘abc1234’;
Database.SaveResult[] results = Database.insert(new SObject[] { p, c });Thanks.
-
Hello,
Yes, you need to make one field as an External id on your parent object.
Thanks.
Log In to reply.