ここでは 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
}
}
================================================== ========================
アップデート
@ユーザー1991372
この更新が役立つことを願っています。ループ内の 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;
}