+ Start a Discussion

Need help with adding child records to parent records in bulk, Kudos given

I have the standard object Contract and a custom object that has a master detail relationship with called Contract_Line_Item__c.  I need to be able to load this code with a larger than 1 batch size.  My problem is I am used to using SOQL heavily, now I am trying to learn the more efficient approach that allows for bulk loading.

The problem I have is that I haven't been able to figure out how to load the child records due to the need of knowing the newly created parent id's.

Here is the code, please help me out if you can.  Thank you,

Trigger ContractTriggerCreatContractAndOLIs on Contract (after update)

    Date StartDate;
    Date EndDate;
    String cAccountid;
    String cContractId;
    String cParentId;
    List<Contract> ContractsToClone = [Select id, Parent_Contract__c, Status, Attn_To__c, Original_Case__c, Maintenance_out_of_sync__c, NewlyCreatedNumDays__c, DateFinal__c,PrevNumberOfDays__c,
            PrevStartDate__c, PrevEndDate__c, PrevNumberOfLeapYearDays__c, Term_In_Days__c, XNumberOfDays__c, AccountId, XNumberOfLeapYearDays__c, NumberOfLeapYearDays2__c,
            SpecialTerms, FEndDate__c, FCompareDayEndDate__c, Total_Maintenance_Price__c,Months_between_start_and_end__c,Override_Total_Price__c,StartDate,
            Contract_End_Date__c, Case__c, RecordTypeId
            from Contract where Test_Contract_Clone__c = TRUE and Processed_Renewal_Contract__c = False and Id in :Trigger.newMap.keySet()];

    List<Contract> ContractsToInsert = new List<Contract>();
    Contract newContract = new Contract();

    for(Contract c: ContractsToClone)
        NewContract = new Contract();
        NewContract.StartDate = Date.Today();
        NewContract.Contract_End_Date__c = Date.Today();
        NewContract.Status = 'Pending';
        NewContract.Accountid = c.AccountId;
        NewContract.RecordTypeId = c.RecordTypeId;
        NewContract.Parent_Contract__c = c.id;
    Insert ContractsToInsert;
   List<Contract_Line_Item__c> CLIs = [Select Account__c, Contract__c, Product_LU__c, Quantity__c from Contract_Line_Item__c where Contract__c in :ContractsToInsert];

Also, the trick is that we are inserting multple parent records that have multiple child records.
The following post might help !!


Please mark this as the best answer if this helped so that it will be helpful for others looking for same solution.