apex – Remove SOQL query inside a loop

You can remove the query on the account and just use SOQL for loop, use the set or map to filter records based on your requirements –

Set<String> establishmentCodes = new Set<String>();
for(Establishment estCode : establishments) {
    establishmentCodes.add(estCode);
}

OR if you need to maintain the mapping of Id to EstablishmentCode then you can create a map of Id -> EstablishmentCode__c like Map<Id,String> and filter your records by values of map and then check in your SOQL loop for existence of EstablishmentCode using the map for individual records.

for (Establishment est : [SELECT Id, Cobro_Anticipado__c, EstablishmentCode__c 
                           FROM Establishment__c 
                           WHERE EstablishmentCode__c IN: establishmentCodes 
                           AND Account__r.CUITCUIL__c =:cuit]) {
    //Your code inside for loop
}        
 

This will solve your problem.

Read more here: Source link