在Apex类中,可以使用触发器(trigger)和Roll-Up Summary字段(滚动汇总字段)来实现联系人对象(Contact)上基于Master-Detail关系的一个“Total Contacts”字段自动更新,以便在每次联系人被更新时都能够正确地计算总的联系人数量。
以下是代码示例:
触发器部分:
trigger TotalContactsTrigger on Contact (after insert, after update, after delete) { TotalContactsRollupHandler.handleTrigger(triggerOperation, triggerNew, triggerOldMap); }
处理程序部分:
public with sharing class TotalContactsRollupHandler {
public static void handleTrigger(Operation triggerOperation, List contacts, Map oldContacts) {
// Only handle after update events
if (triggerOperation == Operation.AFTER_UPDATE) {
// Create a set of all parent account ids to update
Set accountIds = new Set();
for (Contact contact : contacts) {
accountIds.add(contact.AccountId);
}
// Update the parent accounts with the new contact count using the roll-up summary field
List accountsToUpdate = new List([SELECT Id FROM Account WHERE Id IN :accountIds]);
if (accountsToUpdate.size() > 0) {
update accountsToUpdate;
}
}
}
}
通过这个方法,每当联系人被更新时,“Total Contacts Roll-Up Summary”字段会自动更新,从而反映出更新后联系人的总数。