Sunday, May 17, 2020

Insert custom parent and child record using single DML

Sometime back I came across a scenario where i wanted to insert both parent and child object records together.

There could be two ways to do it :

  • Insert parent record then insert child record using already insert parent record ID. Something similar to below. 
I noticed with this approach we will be using multiple DML statements and If I wanted to insert parent and child in bulk that would be whole another level of effort as I'd have to maintain relationship details.

  • Another way would be to create a reference of parent record and use it to set foreign key reference on child record, once done insert both parent and child in single DML.

Refer to below link for more information.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm

I have created code snippet to do same for custom objects, make sure you read through comments to learn about general errors that might come.


Note above method will not work if you try to reference another record of same object type for example if you try to create both ParentAccount and Child Account in same transaction and try to link them using ParentId field, It will not work. In Self lookup scenarios you can only reference records which are already existing else divide them in different DML's


Thanks for reading...


If you liked the post do support me by buying a pizza for me :D

No comments:

Post a Comment