Your question, as stated, isn't very clear. Given the query you have though, I'm assuming your question is something like
- I have a custom object which has a relationship (lookup or master-detail) to
Account
- I have a collection of Account Ids
- I want to know how many of my custom object records are related to each Account
If that's the case, then the simplest way to do this in code would be to use a SOQL query with aggregate functions.
Using COUNT()
and GROUP BY
, you can have SOQL do most of the heavy lifting. Such a query would look like
List<AggregateResult> results = [
SELECT COUNT(Id) numberOfChildren, AccountId
FROM Custom_Object__c
WHERE AccountId IN :setOfIds
GROUP BY AccountId];
As you might be able to read from the query, it counts the number of records in Custom_Object__c
which have an AccountId in the set of Ids you're working with. By grouping the results by AccountId, you get what you're looking for, the count of records for each unique AccountId you provided.
When you use GROUP BY
, you get a List<AggregateResult>
from the query instead of a List<SObject>
.
You need to use .get()
to fetch values from an AggregateResult
, and the result is an Object
, which you'll need to type-cast to really do anything with.
The "numberOfChildren" in the SELECT clause is an alias, which can only be used in conjunction with an Aggregate Function.
Given that results
variable, the loop you'd use to extract results from it would look something like
for(AggregateResult ar :results){
Id accountId = (Id)ar.get('AccountId');
// The alias used in the query is the same thing you use to get the result
// If you don't use an alias, you'd instead use 'expr0', 'expr1', etc...
// (the automatically assigned alias, indexed from 0, and incremented
// for each aggregate function used, assigned from left to right)
Integer count = (Integer)ar.get('numberOfChildren');
system.debug(String.format('The Account with Id {0} has {1} child(ren)',
new List<Object>{
accountId,
count
}
);
}
ID
,Name
,Record__c
andAccount__c
fields.Account__c
is not a list and would not have a size.