Counting groups of objects
Class->count_group_by()
The count_group_by
method can be used to retrieve a list of all the
distinct values that appear in a given column along with a count of
how many objects carry that value. The routine can also be used with
more than one column, in which case it retrieves the distinct pairs
(or n-tuples) of values in those columns, along with the counts.
Yet more powerful, any SQL expression can be used in place of
the column names to count how many object produce any given result
values when run through those expressions.
$iter = MT::Foo->count_group_by($terms, {%args, group => $group_exprs});
$terms
and %args
pick out a subset of the MT::Foo objects in the
usual way. $group_expressions
is an array reference containing the
SQL expressions for the values you want to group by. A single row will
be returned for each distinct tuple of values resulting from the
$group_expressions
. For example, if $group_expressions
were just a
single column (e.g. group => ['created_on']
) then a single row would
be returned for each distinct value of the created_on
column. If
$group_expressions
were multiple columns, a row would be returned for
each distinct pair (or n-tuple) of values found in those columns.
Each application of the iterator $iter
returns a list in the form:
($count, $group_val1, $group_val2, ...)
Where $count
is the number of MT::Foo objects for which the group
expressions are the values ($group_val1, $group_val2, …). These
values are in the same order as the corresponding group expressions in
the $group_exprs
argument.
In this example, we load up groups of MT::Pip objects, grouped by the pair (catid, invoiceid), and print how many pips have that pair of values.
$iter = MT::Pip->count_group_by(undef,
{group => ['cat_id',
'invoice_id']});
while (($count, $cat, $inv) = $iter->()) {
print "There are $count Pips with " .
"category $cat and invoice $inv\n";
}