function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PuranKishorePuranKishore 

How to In account count the contacts with triggers

trigger ConCount on Account (After Update) {

    for(Account a:trigger.new)
    {
        list<Contact> lscon = [Select id from Contact where accountid=:a.id];
        update lscon;
        

    }
    
}

imutsavimutsav
Your code is correct but if you use data loader or any other tool to update more than 10 Accounts at a time then your trigger will fail since the loop in your code would query more than 10 times.

You should collect the Account IDs first and then use them to query only once to get All the related contacts. Something like this below

Map<Id,Integer> acctIdMap = new Map<Id,Integer>();
for(Account a:Trigger.New) {
acctIdMap.put(a.Id,0);
}
List<Contact> conts = [Select Id,Name from Contact where AccountId IN :acctIdMap.keyValue() ORDER BY AccountID LIMIT 49999];

Integer i = 0;
while(i<conts.size() ) {
Integer x = 0;
x = acctIdMap.get(conts.get(i).AccountId)+1;
acctIdMap.put(acctIdMap.get(conts.get(i).AccountId),x);
i++;
}



Thanks
Utsav

[Do mark this answer as solution if it works for you and give a kudos.]