0
    trigger CaseTriggerOperation on Case (before insert) {
        for (Case caseObj : Trigger.new) {
            List<Case> caseList = [SELECT Id, ContactId 
                                     FROM Case
                                    WHERE ContactId = :caseObj.ContactId
                                      AND CreatedDate = Today];
        if (caseList.size()>=2) {
            caseObj.Status = 'Closed';
        }
        }
}

1 Answer 1

4

When used in bulk, yes, it could hit the SOQL governor limit. You should use the normal Aggregate-Query-Update pattern.

Set<Id> contactIds = new Set<Id>();
// Put contactIds in to Set
for(Case record: Trigger.new) {
  contactIds.add(record.ContactId);
}
// Use AggregateQuery to find cases with 2+ for same Contact
contactIds.retainAll(
  new Map<Id, AggregateResult>(
    [SELECT ContactId Id
     FROM Case
     WHERE ContactId = :contactIds AND CreatedDate = TODAY
     GROUP By ContactId
     HAVING COUNT(Id) >= 2
    ]
  ).keySet()
);
for(Case record: Trigger.new) {
  if(contactIds.contains(record.ContactId)) {
    record.Status = 'Closed';
  }
}
1
  • Thanks sfdcfox for your help
    – code234
    Apr 18, 2021 at 6:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .