您在这里不需要 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
}
}
//------------------- 实用程序顶点
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;
}