计算帐户的活跃联系人总数

counting total active contacts for the account

我在联系人上创建了一个复选框来表示它的状态 (active__c ),并为帐户对象创建了另一个自定义字段,它表示活动联系人的总数 (activeContact__c)。

下面的代码工作正常,但是当我将任何帐户的活跃联系人总数设为零时,它仍然是 1。

你能解释一下我做错了什么吗?谢谢

trigger CountActiveContacts on Contact (after insert , after update) {
     switch on Trigger.operationType {
        when AFTER_INSERT, AFTER_UPDATE {
            List<Account> accountList = new List<Account>();
            Set<Id> accIds = new Set<Id>();
 
            
            for(Contact c : Trigger.new){                
                    accIds.add(c.AccountId);
            }
            
            AggregateResult[] groupedResult = [select accountid accID, count(id) totalCountOfActiveContacts from contact where active__c = true and AccountId =: accIds group by accountid ];
            
            for(AggregateResult result: groupedResult){
                accountList.add(new Account(id= (id)result.get('accID'), activeContact__c= (Integer) (result.get('totalCountOfActiveContacts'))));
            }
            update accountList;
        }        
     }
}

当取消勾选最后一个联系人时,您的查询开始 return 0 行

select accountid accID, count(id) totalCountOfActiveContacts 
from contact 
where active__c = true and AccountId =: accIds 
group by accountid

所以没有什么可以循环了。

尝试将帐户作为映射并将计数器初始化为零。你甚至不需要 Set

Map<Id, Account> accs = new Map<Id, Account>();
for(Contact c : trigger.new){
    accs.put(c.AccountId, new Account(Id = c.AccountId, ActiveContact__c = 0));
}

AggregateResult[] groupedResult = [select accountid accID, count(id) totalCountOfActiveContacts from contact where active__c = true and AccountId =: accs.keyset() group by accountid ];
            
for(AggregateResult result: groupedResult){
    accs.get((Id) result.get('accID')).ActiveContact__c = (Integer) result.get('totalCountOfActiveContacts');
}