Saturday 4 October 2014

Creating Parent and Child Records in Single Statement


Inserting Parent and Child record in single statement is commonly asked question in Interviews. This could be achieved using external ID fields instead of inserting parent record then querying its ID and then inserting Child record.

Let take an example, I want to insert Account and Contact records in single insert DML statement.
To do so I will first create Contact Object and populates some of its fields, then creates two Account objects. First account is only for foreign key relationship and other for account creation. Both account have ExternalId field. Then we will call database.insert by passing it an array of sObjects. First element in array will be parent sObject and second element will be child sObject.

// Child record
Contact newContact = new Contact(FirstName = 'Child', LastName = 'Contact', Email = 'puneetmishrasfdc@gmail.com'  );

// Creating reference Account
Account accountRef = new Account(ExternalId__c = 'Vr123Cloud');
newContact.Account = accountRef ;

// Creating parent Account which will get inserted
Account parentAccount = new Account(Name = 'Parent Account', ExternalId__c = 'Vr123Cloud');

//below statement will create an Account and Contact
Database.SaveResult[] = database.insert(new sObject[] { parentAccount, newContact });


Account and Contact records gets inserted with relationship successfully and only 1 DML statement is used for above process.

We have used Datebase method to insert the parent and child records, we can also used simple DML insert statement to do same.


Account acc = new Account(Name = 'Parent Account', ExternalId__c = 'Vr123Cloud');

Contact cont = new Contact(FirstName = 'Child ', LastName = 'Contact ',  Account = new Account(ExternalId__c = 'Vr123Cloud'));

insert new List<sObject>{acc, cont};

No comments:

Post a Comment