0

I am trying to use the DML statement to make an insert to the parent and child tables all at once.

I have got it to this point so far, I am not sure how to link the child to the parent when doing the insert in one command.

I tried following the instructions on the post below, got a bit confused. On the code there they use an external ID to make it happen which I am not sure about as I want the child objects to have the id of the parent record on its foreign key relationship field. I already have a master-detail relationship setup between the custom objects.

Insert List of Parent and Child Records in One DML Statement

Here is what I go to so far. How do I link the 2 objects using the master-detail relationship setup and how to use the insert statement.

List<addressMaster__c> mduMaster = new List<addressMaster__c>();
        List<addressDetail__c> mduDetails = new List<addressDetail__c>();         
        Object[] values = (Object[])System.JSON.deserializeUntyped(mdus);
        for( Object mdu : values) {
            Map<String,Object> data = (Map<String,Object>)mdu;
            streetAddress = String.valueof(data.get('streetAddress'));
            totalUnits = Integer.valueof(data.get('totalUnits'));
            nnUnits = Integer.valueof(data.get('nnUnits'));            
            addressDetail__c newMduDetail = new addressDetail__c(Name=streetAddress,nnUnits__c=nnUnits,lastReportDate__c=DateTime.now());                                                         
            addressMaster__c newMduMaster = new addressMaster__c(Name=streetAddress,totalUnits__c=totalUnits);

            mduDetails.add(newMduDetail);
            mduMaster.add(newMduMaster);
        }
1

You need to insert the masters first, then insert the children with the master record IDs. Starting from the end of the code you've posted:

insert mduMaster;
for(integer i = 0, s = mduMaster.size(); i < s; i++) {
  mduDetails[i].AddressMaster__c = mduMaster[i].Id;
}
insert mduDetails;
1

I am trying to use the DML statement to make an insert to the parent and child tables all at once.

Simply put you can't insert a Parent and Child in one DML operation if you avoid the External ID pattern outlined in the developer guide.

You would have to:
1) Insert the parent record(s). (1x DML)
2) Query IDs.
3) Reference parent IDs when you create the children. (1x DML)

It is possible to do this all at once, as you are asking about... but you have to follow the External ID pattern. The developer documentation is pretty clear. Please re-read, follow along, and let us know if you get stuck.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm?search_text=parent%20child%20dml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.