Class::DBI::Sweet::Pie - Class::DBI::Sweetで集約関数を扱うためのモジュール
package MyData::CD; use base qw/Class::DBI::Sweet/; __PACKAGE__->has_a( artist => 'MyData::Artist' ); use Class::DBI::Sweet::Pie; __PACKAGE__->mk_aggregate_function('sum'); __PACKAGE__->mk_aggregate_function( max => 'maximum'); package MyData::Artist; use base qw/Class::DBI::Sweet/; __PACKAGE__->has_many( cds => 'MyData::CD' ); use Class::DBI::Sweet::Pie; __PACKAGE__->mk_aggregate_function('min'); __PACKAGE__->mk_aggregate_function( max => 'maximum'); package main; # 一番高価なCDの価格 $max_price = MyData::CD->maximum( 'price' ); # fooさんのCDの合計金額 $total_price = MyData::CD->sum( 'price', { 'artist.name' => 'foo', } ); # fooさんのCDで一番安価なものの価格 $artist = MyData::Artist->search( name => 'foo' ); $min_price = $artist->min('cds.price');
Class::DBI::Sweetを使ったテーブルで集約関数を簡単に使えるようになります。
mk_aggregate_functionメソッドを使って集約関数を追加します。 第1引数にSQLで利用する集約関数を、第2引数にメソッド名を指定します。 メソッド名が省略された場合は、集約関数名がメソッド名になります。
__PACKAGE__->mk_aggregate_function( 'max' );
または
__PACKAGE__->mk_aggregate_function( 'max' => 'maximum' );
集約関数の第1引数に、対象となるカラム名を記述します。 $max_price = MyData::CD->maximum( 'price' ); 第2引数以降はClass::DBI::Sweetのsearchメソッドと同様の記述ができます。 # SELECT SUM(price) FROM __TABLE__ WHERE artist = 'foo' $total_price = MyData::CD->sum( 'price', 'artist' => 'foo', );
# SELECT SUM(price) FROM __TABLE__ WHERE price >= 1000 $total_price = MyData::CD->sum( 'price', { 'price' => {'>=', 1000}, } );
関連付けられた他のテーブルのカラムも集計できます。
$max_price = MyData::Artist->maximum( 'cds.price' );
has_manyなテーブルに対してはこんなこともできます。
$artist = MyData::Artist->search( name => 'foo' ); $min_price = $artist->min('cds.price');
アーティスト名とその人の一番高いCDの価格を表示するにはこんな風に書きます。
my @artists = MyData::Artist->search( $criteria ); foreach my $artist (@artists) { print $artist->name, "\t", $artist->maximum('cds.price'), "\n"; }
ループのたびに集約関数を使ってイマイチだと思うなら、こんなこともできます。
my @artists = MyData::Artist->search_with_maximum( 'cds.price', $criteria ); foreach my $artist (@artists) { print $artist->name, "\t", $artist->maximum, "\n"; }
ついでに価格の高い順に並べ換えたりもできます。
my @artists = MyData::Artist->search_with_maximum( 'cds.price', $criteria, {order_by => 'maximum DESC'} );
ASAKURA Takuji <asakura.takuji+cpan@gmail.com>
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Class::DBI::Sweet
Class::DBI::Plugin::AggregateFunction
To install Class::DBI::Sweet::Pie, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::DBI::Sweet::Pie
CPAN shell
perl -MCPAN -e shell install Class::DBI::Sweet::Pie
For more information on module installation, please visit the detailed CPAN module installation guide.