[SalesForce] Inserting Parent and child records in apex without using external id

I am trying to insert a parent and related child records in same apex execution phase.

// code to cretae parent record list
 List<Parent_Record__c> parentList = new List<Parent_Record__c>();
 List<Child_Record__c> childList = new List<Child_Record__c>();

    Parent_Record__c pr1=new Parent_Record__c();
    pr1.field1__c='f1';
    pr1.field2__c='f2';
    parentList.add(pr1);

    Child_Record__c  ch1=new Child_Record__c();
    ch1.field1='f1';
    ch1.Parent_Record__c=pr1.Id;
    childList.add(ch1);

    Child_Record__c  ch2=new Child_Record__c();
    ch2.field1='f1';
    ch2.Parent_Record__c=pr1.Id;
    childList.add(ch2);

    insert parentList;


    insert childList;

With the above code, the insertion of child record is failing saying parent id is null.

Here there is a Master-detail relation between parent and child. The parent object is already reaching all limits so we don't want to create an external id.

Is there any other way to achieve this?

Best Answer

Hi The list which got inserted for parent records (parentlist) will contain the record id afterthe insert operation.

Get the value of parent id from the parentlist and assign to the child list.

Then insert childlist.

Related Topic