0

实际上,我正在尝试将Area_c自定义对象(邮政编码)中的字段放入引导对象自定义字段中Area_c。所以,我已经编写了一些代码,但是还有其他方法可以编写它或对这段代码进行一些优化。

trigger OpportunityPriceBook on Lead (before insert) { 

List<String> zipList = new List<String>();

for(Lead lead : Trigger.new){

   zipList.add(lead.PostalCode);

}

List<Zip_Code__c> zipCodeList = [Select Id, Name, City__c, Area__c from 

Zip_Code__c WHERE Name IN : zipList];

for(Lead leads : Trigger.new){

    for(Integer i =0 ; i < zipCodeList.size(); i++)
      {
         leads.Area__c = zipCodeList.get(i).Area__c;
         leads.City = zipCodeList.get(i).City__c;
         break;
      }   

    }

  }
4

1 回答 1

1

给定代码,有几种方法可以简化最后一个多维 for 循环;由于它们的指数性质,嵌套的 for 循环有时可能会出现问题。

就这一点而言,您的代码中有一个非常明显的错误:您在嵌套的 for 循环中没有识别条件语句,实际上每次都只将前导设置为第一个邮政编码的数据。

这是我会采取的方法:

// Extract out the postal codes of the leads
List<String> zipList = new List<String>();
for (Lead lead : Trigger.new) {
    zipList.add(lead.PostalCode);
}

// Query for the related Zip Codes, and map them by Name
List<Zip_Code__c> zipCodeList = [SELECT Id, Name, City__c, Area__c FROM Zip_Code__c WHERE Name IN :zipList];
Map<String, Zip_Code__c> zipCodeByName = new Map<String, Zip_Code__c>();
for (Zip_Code__c zipCode : zipCodeList) {
    zipCodeByName.put(zipCode.Name, zipCode);
}

// Stamp leads with the Area and City as identified by the matching Zip Code
for (Lead lead : Trigger.new) {
    Zip_Code__c zipCode = zipCodeByName.get(lead.PostalCode);
    lead.Area__c = zipCode.Area__c;
    lead.City = zipCode.City__c;
}
于 2019-09-08T14:54:00.680 回答