Salesforce Apex如何在for循环之外编写SOQL

时间:2013-11-30 16:46:37

标签: salesforce apex

我正在使用一个使用许多SOQL语句的Trigger。我尝试过遵循本指南http://wiki.developerforce.com/page/Best_Practice:_Avoid_SOQL_Queries_Inside_FOR_Loops并且它对我不起作用,因为Salesforce中的ID与每个项目的ID都不完全相同。这就是我的意思:

(顺便说一句,这是一个叫父母的子记录,所以父母的事情对我不起作用)

list<opportunity> listOpportunity = [select id
                                     From opportunity
                                     Where id IN : *Trigger.oldmap.keyset()];*

for(Opportunity opportunity : listOpportunity)
{
     //Do Code here.

}

我想要的只是为这个列表填充正确的机会被触发。

1 个答案:

答案 0 :(得分:3)

此处不需要SOQL查询,您只需使用以下代码段

即可
// for iterate trough new opportunities
for (Opportunity newOpp: Trigger.new) {
     // do something with new Opps
}
 // for iterate trough old opportunities
 for (Opportunity oldOpp: Trigger.oldMap.values()) { 
     // read old values on update trigger
 }

你也可以把它结合起来

 // for iterate trough old opportunities

for (Opportunity newOpp: Trigger.new) {
    if (newOpp.field1 != Trigger.oldMap.get(newOpp.Id).field1) {
        // do something for changed field
    }
}

=============================================== ===========================

<强>更新

@ user1991372

我希望此更新会有所帮助,以下是在循环中使用SOQL解决此类问题的常见方法示例

// ------------------触发

Map<Id, List<Account>> accountsByOpp = new Map<Id, List<Account>>();
 List<Account> accounts = [SELECT Oppty
                                 ,name 
                           FROM account 
                           WHERE oppty IN Trigger.newMap.keySet()];
accountsByOpp = splitListByKey(accounts, 'oppty');

for (Opportunity opp: Trigger.old) {
    List<Account> accs = accountsByOpp.get(opp.Id);
    if (accs != null) {
        // do something
    }
}

// ------------------- Utility apex

class CommonException extends Exception {}

public static Map<Id, List<sObject>> splitListByKey(List<sObject> sourceList, String key) {
    if (sourceList == null) {
        throw new CommonException('ERROR: splitListByKey(sourceList, key) got incorrect first parameter.');
    }
    if (key == null || key == '') {
        throw new CommonException('ERROR: splitListByKey(sourceList, key) got incorrect second parameter.');
    }
    Map<Id,List<sObject>> result = new Map<Id,List<sObject>>();
    List<sObject> tmpObjs;
    for (sObject obj: sourceList) {
        tmpObjs = new List<sObject>();
        if (obj.get(key) != null && result.containsKey((Id)obj.get(key))) {
            tmpObjs = result.get((Id)obj.get(key));
            tmpObjs.add(obj);
            result.put((Id)obj.get(key), tmpObjs);
        } else if (obj.get(key) != null) {
            tmpObjs.add(obj);
            result.put((Id)obj.get(key), tmpObjs);
        }
    }
    return result;
}