You need to sign in to do that
Don't have an account?
Surabhi20
How to meet apex best practices in below scenario
public void createSubexampleOnExample(List<ID> opportunityId, Map<ID,ID> oppLot){
for(Id oppId : opportunityId){
List<sub_Example__c> subExamples = new List <sub_Example__c>();
List<Opp_Account_Relationship__c> acc = [Select Account__c, Opportunity__c from Opp_Account_Relationship__c where Opportunity__c =: oppId];
for(Opp_Account_Relationship__c oppAcc : acc){
sub_Example__c sub = new sub_Example__c();
sub.Example__c = oppLot.get(oppAcc.Opportunity__c);
sub.Account__c = oppAcc.Account__c;
lotAccounts.add(sub);
}
insert subExamples;
}
}
for(Id oppId : opportunityId){
List<sub_Example__c> subExamples = new List <sub_Example__c>();
List<Opp_Account_Relationship__c> acc = [Select Account__c, Opportunity__c from Opp_Account_Relationship__c where Opportunity__c =: oppId];
for(Opp_Account_Relationship__c oppAcc : acc){
sub_Example__c sub = new sub_Example__c();
sub.Example__c = oppLot.get(oppAcc.Opportunity__c);
sub.Account__c = oppAcc.Account__c;
lotAccounts.add(sub);
}
insert subExamples;
}
}
As per the best practice, we should avoid writing SOQL query inside any loop. In this case Line no. 5 is writtnen inside the FOR loop. This may also hit the governor limit.
Also we should avoid writing any DML operation inside the loop. here in your case Line 13 : insert subExamples written inside FOR loop, which should have been written outside the loop.
You can decalre the variable globally.
Please mark as Best Answer so that it can help others in the future.
Regards,
Priya Ranjan
I need help in modifying the above code.. I know and understood that its not written considering the best practices.
I want to understand how to write the code in first for loop for each entry in opportunityId List???
no need of first for loop. By using IN keyword in soql it will return list of records of Opp_Account_Relationship__c which are associated with opportunityId.
Recommended: If you want to store list of ID's use set<id> it will eliminate duplication. I hope this will help you. If yes make it as the best answer
as per best practice you must keep following things in mind.
1. you should avoid soql query in for loop.
2. you can't run dml inside loop.
3. if you want to run any dml through loop, create variable outside the loop and add data in loop such as in following class has mentioned.
let me know if it helps you and marking it as best answer so that it can help to others in future.
Thank you