sub checkout_total {
+shift->items->get_column("cost")->sum;
}
####
# Inside My::Schema::Cart or an auxillary class only
# loaded into the space on demand.
sub checkout_total {
# My::Schema::Cart object.
my $self = shift;
# items is a has_many relationship.
my $items_rs = $self->items; # ->items_rs to avoid contex ambiguity.
# Get a DBIx::Class::ResultSetColumn object for cost.
my $cost_col = $items_rs->get_column("cost");
# Perform SUM.
my $sum = $cost_col->sum;
return $sum;
}
##
##
# This is not exactly how it would be set up for real.
# Load order and @INC stuff requires some tweaks to
# have in one file.
BEGIN {
package My::Schema::Item;
use strict;
use warnings;
use parent "DBIx::Class::Core";
__PACKAGE__->table("item");
__PACKAGE__->add_columns(
"id", { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
"cart", { data_type => "integer", is_nullable => 0 },
"cost",
);
__PACKAGE__->set_primary_key("id");
# See below.
# __PACKAGE__->belongs_to(cart => "My::Schema::Cart");
package My::Schema::Cart;
use strict;
use warnings;
use parent "DBIx::Class::Core";
__PACKAGE__->table("cart");
__PACKAGE__->add_columns(
"id", { data_type => "integer", is_auto_increment => 1, is_nullable => 0 },
);
__PACKAGE__->set_primary_key("id");
__PACKAGE__->has_many( items => "My::Schema::Item",
{ "foreign.cart" => "self.id" } );
sub checkout_total {
+shift->items->get_column("cost")->sum;
}
# Would actually be above.
My::Schema::Item->belongs_to(cart => "My::Schema::Cart");
# This would really be lib/My/Schema.pm
package My::Schema;
use strict;
use warnings;
use parent "DBIx::Class::Schema";
__PACKAGE__->load_classes(qw( Item Cart ));
}
use strict;
use warnings;
my $schema = My::Schema->connect("dbi:SQLite::memory:");
$schema->deploy;
my $cart_id = 1024;
$schema->populate( Cart => [ ["id"],[$cart_id] ] );
my $cost = sub { sprintf "%.2f", rand(100) };
for ( 1 .. 6 )
{
$schema->populate( Item => [ [qw( id cart cost )],
[ $_, $cart_id, $cost->() ] ] );
}
for my $cart ( $schema->resultset("Cart")->all )
{
printf("cart:%d --> \$%6.2f\n",
$cart->id,
$cart->checkout_total);
for my $item ( $cart->items )
{
printf(" item:%d --> \$%5.2f\n",
$item->id,
$item->cost);
}
}
__DATA__
cart:1024 ---> $222.16
item:1 --> $46.46
item:2 --> $ 5.56
item:3 --> $84.50
item:4 --> $ 6.72
item:5 --> $15.50
item:6 --> $63.42