0

When executing the following code in an after insert trigger, I am getting the error

"System.QueryException: Invalid bind expression type of TransactionItem__c does not match domain of foreign key Class"

Integer myAggregate = [SELECT Count() 
            FROM TransactionItem__c 
            WHERE Transaction__c = :Trigger.new];
System.debug(myAggregate);

What could be wrong? Thanks.

2
  • Try Transaction__r.Id IN :Trigger.newMap.keySet() (assuming the trigger is on Transaction__c object)
    – arut
    Dec 19, 2020 at 7:19
  • Trigger is on the child object TransactionItem__c. master-detail relationship filed is Transaction on the child object. The fix ran without errors but debug only printed count 0, it should be 3 actually as it has 3 related child records.
    – user91213
    Dec 19, 2020 at 8:29

1 Answer 1

1

Since the Trigger.new domain is TransactionItem__c, you would also need to bind to an Id field of the same domain. In this case, what you need to do is to pull the Transaction__c Id values out of the records, and then filter on that.

Set<Id> transactionIds = new Set<Id>();
for(TransactionItem__c record:Trigger.new) {
  transactionIds.add(record.Transaction__c);
}
Map<Id, AggregateResult> results = new Map<Id, AggregateResult>([
  select count(id) itemCount, Transaction__c Id
  from TransactionItem__c
  where Transaction__c = :transactionIds
  group by Transaction__c
]);

Note that there may be more than one record in Trigger.new, so we use a map to keep track of how many TransactionItem__c records are per Transaction__c.

0

You must log in to answer this question.