added many_to_many set_$rel helper and tests
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / ManyToMany.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::ManyToMany;
3
4 use strict;
5 use warnings;
6
7 sub many_to_many {
8   my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
9   {
10     no strict 'refs';
11     no warnings 'redefine';
12
13     my $add_meth = "add_to_${meth}";
14     my $remove_meth = "remove_from_${meth}";
15     my $set_meth = "set_${meth}";
16
17     *{"${class}::${meth}"} = sub {
18       my $self = shift;
19       my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
20       $self->search_related($rel)->search_related(
21         $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
22       );
23     };
24
25     *{"${class}::${add_meth}"} = sub {
26       my $self = shift;
27       @_ > 0 or $self->throw_exception(
28         "${add_meth} needs an object or hashref"
29       );
30       my $source = $self->result_source;
31       my $schema = $source->schema;
32       my $rel_source_name = $source->relationship_info($rel)->{source};
33       my $rel_source = $schema->resultset($rel_source_name)->result_source;
34       my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
35       my $f_rel_rs = $schema->resultset($f_rel_source_name);
36       my $obj = ref $_[0]
37         ? ( ref $_[0] eq 'HASH' ? $f_rel_rs->create($_[0]) : $_[0] )
38         : ( $f_rel_rs->create({@_}) );
39       my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
40       my $link = $self->search_related($rel)->new_result({});
41       $link->set_from_related($f_rel, $obj);
42       $link->set_columns($link_vals);
43       $link->insert();
44     };
45
46     *{"${class}::${set_meth}"} = sub {
47       my $self = shift;
48       @_ > 0 or $self->throw_exception(
49         "{$set_meth} needs a list of objects or hashrefs"
50       );
51       $self->search_related($rel, {})->delete;
52       $self->$add_meth(shift) while (defined $_[0]);
53     };
54
55     *{"${class}::${remove_meth}"} = sub {
56       my $self = shift;
57       @_ > 0 && ref $_[0] ne 'HASH'
58         or $self->throw_exception("${remove_meth} needs an object");
59       my $obj = shift;
60       my $rel_source = $self->search_related($rel)->result_source;
61       my $cond = $rel_source->relationship_info($f_rel)->{cond};
62       my $link_cond = $rel_source->resolve_condition(
63         $cond, $obj, $f_rel
64       );
65       $self->search_related($rel, $link_cond)->delete;
66     };
67
68   }
69 }
70
71 1;