-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCountChild-UsingAggregateFunction-WithoutAggregate
72 lines (58 loc) · 2.4 KB
/
CountChild-UsingAggregateFunction-WithoutAggregate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
trigger CountContact on Contact (after insert, after update, after delete, after undelete) {
set<Id> setAccountid = new set<Id>();
list<Account> lstAc = new list<Account>();
try{
if(trigger.isExecuting && trigger.isAfter){
if(trigger.isDelete){
for(Contact ct:trigger.old){
setAccountid.add(ct.AccountId);
}
}
else{
for(Contact ct:trigger.new){
setAccountid.add(ct.AccountId);
}
}
AggregateResult[] queryContact=[select Count(Id) cti, AccountId aci from Contact where AccountID=:setAccountid
GROUP BY AccountId];
if(queryContact.size()>0){
//now use foreach loop
for(AggregateResult ar:queryContact){
Id AccId=(Id)ar.get('aci');
Integer count = (INTEGER)ar.get('cti');
Account act = new Account(Id=AccId);
act.Count_Contact__c=count;
lstAc.add(act);
}
}
update lstAc;
}}catch(exception ex){
system.debug('@@@@ getLineNumber: '+ex.getLineNumber());
system.debug('@@@@ getMessage: '+ex.getMessage());
}
}
============================================without using Aggregate=============================================================
trigger CountContact on Contact (after insert, after update, after delete, after undelete) {
set<Id> storeAccID = new set<Id>();
list<Account> lstAcct= new list<Account>();
if(trigger.isExecuting && trigger.isAfter){
if(trigger.isDelete){
for(Contact ct:trigger.old){
storeAccID.add(ct.AccountId);
}
}else{
for(Contact ct:trigger.new){
storeAccID.add(ct.AccountId);
}
}
if(storeAccID.size()>0){
list<Account> lstAc=[select Id,(select Id from Contacts) from Account where Id=:storeAccID];
for(Account ac:lstAc){
Integer ContSize= (Integer)ac.Contacts.size();
ac.Count_Contact__c=ContSize;
lstAcct.add(ac);
}
}
update lstAcct;
}
}