是的,如果您想计算与联系人相关的 Junction__c 记录的数量,您可以将触发器放在 Junction__c 对象上。最佳实践是将您的逻辑放在一个类中而不是触发器中。以下是您想要的粗略实现。
trigger ConferenceAttendeesUpdater on Junction__c (after insert, after update, after delete, after undelete ) {
if ( Trigger.isAfter && Trigger.isInsert ){
junctionHelper.afterInsert(Trigger.new);
}
if ( Trigger.isAfter && Trigger.isUpdate ){
junctionHelper.afterUpdate(Trigger.new, Trigger.old);
}
if ( Trigger.isAfter && Trigger.isDelete ){
junctionHelper.afterInsert(Trigger.old);
}
if ( Trigger.isAfter && Trigger.isUndelete ){
junctionHelper.afterInsert(Trigger.new);
}
}
public without sharing junctionHelper(){
public static void afterInsert(List<Junction__c> newList){
Map<Id,Contact> contactRollup = new Map<Id,Contact>();
for ( Integer i=0;i<newList[i].size();i++ ){
if ( newList[i].Contact__c != null ){
contactMap.put(newList[i].Contact__c, new Contact(Id=newList[i].Contact__c,Number_of_Junctions__c=0));
}
}
}
public static void afterUpdate(List<Junction__c> newList, List<Junction__c> oldList){
Map<Id,Contact> contactRollup = new Map<Id,Contact>();
for ( Integer i=0;i<newList[i].size();i++ ){
if ( newList[i].Contact__c != oldList[i].Contact__c ){
contactMap.put(newList[i].Contact__c, new Contact(Id=newList[i].Contact__c,Number_of_Junctions__c=0));
}
}
}
public static void rollUpContacts(Map<Id,Contact> contactMap){
for ( AggregateResult ar : [
SELECT COUNT(Id) cnt, Contact__c parentId
FROM Junction__c
WHERE Contact__c IN :contactMap.keySet()
]{
Id parentId = (String)ar.get('parentId);
Decimal cnt = (Decimal)ar.get('cnt');
contactMap.put(parentId,new Contact(Id=parentId,Number_of_Junctions__c=cnt));
}
update contactMap.values();
}
}