I am creating some code that takes the accountId From a custom object and copies it to the Case object's accountId field based on if the URL from the custom object matched the URL from the case object. Below is the code I have created. It works but there is a SOQL query in the for loop which is bad practice. How would I go about removing the SOQL from the For loop?
Code:
for(Integer i=0; i < triggerNew.size(); i++){
Case newCase = triggerNew[i];
if(newCase.AppURL__c != null){
String cloud = newCase.AppURL__c;
system.debug(cloud);
List<MobileCloud_Website__c> acc = [select Account__r.Id from MobileCloud_Website__c WHERE URL__c =: cloud];
system.debug(acc);
newCase.AccountId = acc[0].Account__r.Id;
}
}
I am aware the best way to do this would be to use a Set and Map, but I am stuck as to how to use those collections properly. Below was as far as I got before my brain gave up.
Code:
Set<MobileCloud_Website__c> accIds = new Set<MobileCloud_Website__c>([select Account__r.Id, URL__c from MobileCloud_Website__c WHERE URL__c != null]);
Map <String, Id> caseURLs = new Map<String, Id>();
for(Integer i=0; i < triggerNew.size(); i++){
Case newCase = triggerNew[i];
if(newCase.AppURL__c != null){
caseURLs.put(newCase.AppURL__c, newCase.AccountId);
}