[Dbix-class] Automatically counting rows of another table - and how
to disable temporarily
Bernhard Graf
dbic3 at augensalat.de
Sun Oct 28 17:10:50 GMT 2007
Hello,
following the examples in the DBIx::Class distribution I have 2 tables:
package My::Schema::Artist;
use base qw/DBIx::Class/;
__PACKAGE__->load_components(qw/PK::Auto Core/);
__PACKAGE__->table('artist');
__PACKAGE__->add_columns(qw/id name albums/);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(albums => 'My::Schema::Album', 'artist');
package My::Schema::Album;
use base qw/DBIx::Class/;
__PACKAGE__->load_components(qw/PK::Auto Core/);
__PACKAGE__->table('album');
__PACKAGE__->add_columns(qw/id artist title/);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->belongs_to(artist => 'My::Schema::Artist');
sub insert {
my $self = shift;
$self->next::method(@_);
$self->artist->update({'albums' => \'albums+1'});
$self;
}
sub delete {
my $self = shift;
$self->next::method(@_);
$self->artist->update({'albums' => \'albums-1'});
$self;
}
This means, that "artist.albums" keeps track of the number of rows in
table "album".
So far, so good.
For cases where I want to create many albums in a row, it would be
desirable to disable this automatism for effeciency reasons and adjust
"artist.albums" manually afterwards.
I suppose I would need an accessor in the result set of
My::Schema::Album that reflects this state, like:
$artist = $schema->resultset('My::Schema::Artist')->find($artistid);
$rs = $schema->resultset('My::Schema::Album');
$rs->disable_count(1);
for ($i = 0; $name = get_albumname(); ++$i) {
$rs->create({artist => $artist, name => $name});
}
$artist->update(albums => \"albums+$i");
$rs->disable_count(0);
Could someone give advice if this concept is correct and how to define
such a ResultSet accessor?
--
Bernhard Graf
More information about the DBIx-Class
mailing list