You need to sign in to do that
Don't have an account?

Move child record query outside of for loop
Hello!
So I have a list of parent records called ServiceContract, and as I'm looping through each parent record, I query for the child records called ContractLineItem for that specific parent record, then I use those line items to do something else. My first instinct is to query for those child records inside of the for loop, and I know that is not the correct way to do it. I was hoping someone could show me how to fix my code the correct way. I appreciate the help.
So I have a list of parent records called ServiceContract, and as I'm looping through each parent record, I query for the child records called ContractLineItem for that specific parent record, then I use those line items to do something else. My first instinct is to query for those child records inside of the for loop, and I know that is not the correct way to do it. I was hoping someone could show me how to fix my code the correct way. I appreciate the help.
//ServiceContract parent record list for (ServiceContract selectedContract : selectedContracts) { //Get child contract line records List<ContractLineItem> contractLines =[SELECT id, Product2Id, Quantity, Discount, UnitPrice, ServiceContractId, Description, Product_Reference_ID__c FROM ContractLineItem WHERE ServiceContractId = :selectedContract.Id]; for (ContractLineItem contractLine : contractLines) { gii__ServiceOrderLine__c serviceLine = new gii__ServiceOrderLine__c (); serviceLine.gii__SalesOrder__c = selectedContract.Sales_Order__c; serviceLine.gii__OrderQuantity__c = contractLine.Quantity; serviceLine.gii__UnitPrice__c = contractLine.UnitPrice; serviceLineList.add(serviceLine); } } insert serviceLineList;
Can you try the below code instead of above code.
If this solution helps, Please mark it as best answer.
Thanks,
All Answers
Can you try the below code instead of above code.
If this solution helps, Please mark it as best answer.
Thanks,
Thank you so much! This worked like a charm. The only thing that needed to be changed was mapservice.add(selectedContract.id,selectedContract); to mapservice.put(selectedContract.id,selectedContract);
I really appreciate it.