function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sumesh ChandranSumesh Chandran 

Trying to insert to 2 different custom objects which is in a master-detail relationship

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.][1]

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,;                                                         
                addressMaster__c newMduMaster = new addressMaster__c(Name=streetAddress,totalUnits__c=totalUnits);
Please advise!
That trick requires a foreign key, precisely because the salesforce Id is not known until the record is inserted. You can't insert the parent and child simultaneously unless you define a foreign key.

The more usual approach would be to insert the parent records in one insert statement, then update the child records with the appropriate parent ids, and then insert them.
Sumesh ChandranSumesh Chandran
Okay thanks Shikibu