[Dbix-class] many_to_many and polymorphism

Jason Gottshall jgottshall at capwiz.com
Thu Jan 11 21:17:49 GMT 2007


Well, I've got a partial solution I thought I'd share, if anyone's
interested. Inspired by an article on the dbix-class wiki
(http://dbix-class.shadowcatsystems.co.uk/index.cgi?ManyToManyWithAttrib
utes), I realized that I could write my own accessors (instead of
generating them via many_to_many) and include the production_type
specification there. Like this:

package My::DBIC::Schema::Actor;

#__PACKAGE__->many_to_many( films => 'actor_roles', film' );
sub films {
    my $self = shift;
    return map $_->film, 
               $self->actor_roles(
                   { 'me.production_type' => 'film' }, 
                   { prefetch => ['film'] }
               );
}

#__PACKAGE__->many_to_many( tvshows => 'actor_roles', 'tvshow' );
sub tvshows {
    my $self = shift;
    return map $_->tvshow, 
               $self->actor_roles(
                   { 'me.production_type' => 'tv' }, 
                   { prefetch => ['tvshow'] }
               );
}

package My::DBIC::Schema::Film;

#__PACKAGE__->many_to_many( actors => 'actor_roles', 'actor' );
sub actors {
    my $self = shift;
    return map $_->actor, 
               $self->actor_roles(
                   { 'me.production_type' => 'film' }, 
                   { prefetch => ['actor'] }
               );
}

package My::DBIC::Schema::TVShow;

#__PACKAGE__->many_to_many( actors => 'actor_roles', 'actor' );
sub actors {
    my $self = shift;
    return map $_->actor, 
               $self->actor_roles(
                   { 'me.production_type' => 'tv' }, 
                   { prefetch => ['actor'] }
               );
}

[This begins to suggest to me that Film and TVShow should be subclasses
of a common Production class. Duh. Someday I'll actually grok
object-oriented design...]

Of course, my home-made accessors don't accept additional conditions or
attributes (yet); neither do they return a ResultSet in scalar context.
And I haven't even begun to think about the ${accessor}_rs() and
add_to_$accessor() methods that also would have been generated by an
explicit many_to_many relationship. But it's a step in the right
direction...

Thanks for listening. Comments and suggestions welcome!
Jason



More information about the Dbix-class mailing list