0
List<CustObjChild__c> cItems = [SELECT COUNT() FROM CustObjChild__c 
             WHERE MyParentId__c IN :Trigger.new];

Getting the error: Illegal assignment from Integer to List. In Salesforce Apex Trigger.

Trigger is in the child object which has a Master-Detail relationship.

Any pointers? Thanks!


I had tried with Integer earlier and tried again now with Integer, but when executing the trigger, keeps getting the error:

Line: 19, Column: 1 System.DmlException: Insert failed. execution of AfterInsert caused by: System.QueryException: Invalid bind expression type of CustObjChild__c does not match domain of foreign key Class.

2 Answers 2

2

To get the children per parent, you want to group by the parent ID, and use COUNT(ID) instead of COUNT(). Also, the return type will then be an AggregateResult, not a "child object."

Map<Id, AggregateResult> counts = new Map<Id, AggregateResult>([
  SELECT MyParentId__c Id, COUNT(ID) sum
  FROM CustObjChild__c
  WHERE MyParentId__c = :Trigger.new
  GROUP BY MyParentId__c
]);

You can then get the values for each record:

for(MyParent__c record: Trigger.new) {
  Integer childRecordCount = (Integer)counts.get(record.Id)?.get('sum');
  if(childRecordCount == null) {
    childRecordCount = 0;
  }
  // ...
}
6
  • I am not sure if this is what I want. Because all I am trying to do is get the total number of child records related to its parent record and if this total number is equal to a count field in the parent object, only then execute the method in the child after insert trigger.
    – user91213
    Dec 18, 2020 at 12:14
  • @STSF Yep, you need the count per parent, because otherwise bulk loads won't behave the way you think it should. You can read more about bulkification.
    – sfdcfox
    Dec 18, 2020 at 12:17
  • Right. For bulkification. I am gonna try this now. Thanks.
    – user91213
    Dec 18, 2020 at 12:23
  • @STSF I presumed you had this code directly in a trigger, not a handler. You'll probably want to pass in the Trigger.new context variable and use that in your handler code, or cast it to the correct object list, as in for(MyParent__c record: (MyParent__c[])Trigger.new)
    – sfdcfox
    Dec 18, 2020 at 13:05
  • Yes, I am using the Kevin O Hara's trigger framework. That fixed the deploy error: Invalid loop variable type expected SObject... but now getting the error: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, : execution of AfterInsert caused by: System.QueryException: Invalid bind expression type of CustObjChild__c does not match domain of foreign key Class....
    – user91213
    Dec 18, 2020 at 13:22
0

COUNT in SOQL return Integer.

Integer intCount = [SELECT COUNT() FROM CustObjChild__c WHERE MyParentId__c IN :Trigger.new];

You must log in to answer this question.