[Dbix-class] Three patterns for many-to-many relationships

Matt S Trout dbix-class at trout.me.uk
Sun Apr 16 16:50:13 CEST 2006


Shevek wrote:
> I'm not on the list, but Matt asked me to post this anyway. It contains
> three patterns for making M-M relationships "work". I suggested that
> these might appear just as "add_to_..." appears for a has_many
> relationship.
> 
>       6 sub set_XXXs {
>       7     my $self = shift;
>       8     my @create = map { ref($_) ? $_->id : $_ } @_;
>      10     my %exists = map { $_->XXX_id => $_ } $self->XXX_links;
>      11     for (@create) {
>      12         if (delete $exists{$_}) {
>      13             # print STDERR "Exists $_\n";
>      14             next;
>      15         }
>      16         # print STDERR "Create $_\n";
>      17         $self->add_to_XXX_links({
>      18             XXX_id => $_,
>      19         });
>      20     }
>      21     for (values %exists) {
>      22         # XXX Make sure this doesn't cascade.
>      23         # print STDERR "Delete " . $_->id . "\n";
>      24         $_->delete;
>      25     }
>      26 }
> 
>      69 sub add_to_XXXs {
>      70     my $self = shift;
>      71     my @create = map { ref($_) ? $_->id : $_ } @_;
>      72     my %create = map { $_ => 1 } @create;
>      73     my @links = $self->XXX_links;
>      74     for (@links) {
>      75         my $id = $_->XXX_id;
>      76         delete $create{$id};
>      77     }
>      78     for (keys %create) {
>      80         $self->add_to_XXX_links({
>      81             XXX_id => $_,
>      82         });
>      83     }
>      84 }
> 
>      86 sub remove_from_XXXs {
>      87     my $self = shift;
>      88     my @delete = map { ref($_) ? $_->id : $_ } @_;
>      89     # print STDERR "Delete: @delete\n";
>      90     my %delete = map { $_ => 1 } @delete;
>      91     my @links = $self->XXX_links;
>      92     for (@links) {
>      93         my $id = $_->XXX_id;
>      94         $_->delete if $delete{$id};
>      95     }
>      96 }

Does anybody fancy working this up into a patch for many_to_many on -current?

-- 
      Matt S Trout       Offering custom development, consultancy and support
   Technical Director    contracts for Catalyst, DBIx::Class and BAST. Contact
Shadowcat Systems Ltd.  mst (at) shadowcatsystems.co.uk for more information

+ Help us build a better perl ORM: http://dbix-class.shadowcatsystems.co.uk/ +



More information about the Dbix-class mailing list