{
no strict 'refs';
no warnings 'redefine';
+
*{"${class}::${meth}"} = sub {
my $self = shift;
my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
- $self->search_related($rel)->search_related($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
+ $self->search_related($rel)->search_related(
+ $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
+ );
+ };
+
+ *{"${class}::add_to_${meth}"} = sub {
+ my( $self, $obj ) = @_;
+ my $vals = @_ > 2 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
+ return $self->search_related($rel)->create({
+ map { $_=>$self->get_column($_) } $self->primary_columns(),
+ map { $_=>$obj->get_column($_) } $obj->primary_columns(),
+ %$vals,
+ });
};
+
+ *{"${class}::remove_from_${meth}"} = sub {
+ my( $self, $obj ) = @_;
+ return $self->search_related(
+ $rel,
+ {
+ map { $_=>$self->get_column($_) } $self->primary_columns(),
+ map { $_=>$obj->get_column($_) } $obj->primary_columns(),
+ },
+ )->delete();
+ };
+
}
}
my $schema = DBICTest->init_schema();
-plan tests => 32;
+plan tests => 35;
# has_a test
my $cd = $schema->resultset("CD")->find(4);
is( $cd->producers_sorted->next->name, 'Bob The Builder', 'sorted many_to_many ok' );
is( $cd->producers_sorted(producerid => 3)->next->name, 'Fred The Phenotype', 'sorted many_to_many with search condition ok' );
+# test new many_to_many helpers
+$cd = $schema->resultset('CD')->find(2);
+my $prod = $schema->resultset('Producer')->find(1);
+$cd->add_to_producers($prod);
+my $prod_rs = $cd->producers();
+is( $prod_rs->count(), 1, 'many_to_many add_to_$rel($obj) count ok' );
+is( $prod_rs->first->name, 'Matt S Trout', 'many_to_many add_to_$rel($obj) ok' );
+$cd->remove_from_producers($prod);
+is( $cd->producers->count, 0, 'many_to_many remove_from_$rel($obj) ok' );
+
# test undirected many-to-many relationship (e.g. "related artists")
my $undir_maps = $schema->resultset("Artist")->find(1)->artist_undirected_maps;
is($undir_maps->count, 1, 'found 1 undirected map for artist 1');