使用相关记录中的值更新新商机列表的正确方法是什么。
for (Opportunity opps:Trigger.new){
[SELECT Id, CorpOwner__r, Contact__r,(SELECT Id, AccountLocation from Account)]
o.CorpOwner__r =Account.Id; o.AccountLocation = opps.Account.AccountLocation;
insert opps
您是否通过__r后缀调用查找字段?您是否可以在插入操作之前执行操作并仍然查看Opportunity.CorpOwner__r与CorpOwner__r帐户记录中的值的关系,或者由于尚未创建记录,该关系是否不存在?什么是适当的批处理方式呢?
答案 0 :(得分:1)
这里展示了许多概念的可能性:
trigger UpdateOpptyWithAccountInfo on Opportunity (before insert) {
// Keep this SOQL query out of the FOR loop for better efficiency/batching
Map<Id, Account> relatedAccounts = new Map<Id, Account>(
[SELECT Id, AccountLocation__c
FROM Account
WHERE Id IN
(SELECT AccountId
FROM Opportunity
WHERE Id = :Trigger.new)
]
);
for (Opportunity o : Trigger.new) {
/* Find each opportunity's Account in the map we queried for earlier
* Note: there's probably a more efficient way to use a Map of Opportunity IDs to Account objects...
* This works fine and could be more readable.
*/
for (Account a : relatedAccounts.values()) {
if (a.Id == o.AccountId) {
// Once you've found the account related to this opportunity, update the values
o.CorpOwner__c = a.Id;
o.AccountLocation__c = a.AccountLocation__c;
}
}
}
// We're still inside an `insert` trigger, so no need to call `insert` again.
// The new fields will be inserted along with everything else.
}
如果您正在建立对象之间的关系,请使用__c
后缀:
o.CorpOwner__c = a.Id; // Associate Account `a` as Opportunity `o`'s CorpOwner
如果您要查找相关对象上的字段,则可以使用__r
:
System.debug(o.CorpOwner__r.Name); // Print Opportunity `o`'s CorpOwner's name