1 package # hide from PAUSE
2 DBIx::Class::Relationship::ManyToMany;
8 my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
10 $class->throw_exception(
11 "missing relation in many-to-many"
14 $class->throw_exception(
15 "missing foreign relation in many-to-many"
20 no warnings 'redefine';
22 my $add_meth = "add_to_${meth}";
23 my $remove_meth = "remove_from_${meth}";
24 my $set_meth = "set_${meth}";
25 my $rs_meth = "${meth}_rs";
27 $rel_attrs->{alias} ||= $f_rel;
29 *{"${class}::${meth}_rs"} = sub {
31 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
32 my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
33 my $rs = $self->search_related($rel)->search_related(
34 $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
39 *{"${class}::${meth}"} = sub {
41 my $rs = $self->$rs_meth( @_ );
42 return (wantarray ? $rs->all : $rs);
45 *{"${class}::${add_meth}"} = sub {
47 @_ > 0 or $self->throw_exception(
48 "${add_meth} needs an object or hashref"
50 my $source = $self->result_source;
51 my $schema = $source->schema;
52 my $rel_source_name = $source->relationship_info($rel)->{source};
53 my $rel_source = $schema->resultset($rel_source_name)->result_source;
54 my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
55 my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
59 if (ref $_[0] eq 'HASH') {
60 $obj = $f_rel_rs->create($_[0]);
65 $obj = $f_rel_rs->create({@_});
68 my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
69 my $link = $self->search_related($rel)->new_result($link_vals);
70 $link->set_from_related($f_rel, $obj);
75 *{"${class}::${set_meth}"} = sub {
77 @_ > 0 or $self->throw_exception(
78 "{$set_meth} needs a list of objects or hashrefs"
80 my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
81 $self->search_related($rel, {})->delete;
82 $self->$add_meth($_) for (@to_set);
85 *{"${class}::${remove_meth}"} = sub {
87 @_ > 0 && ref $_[0] ne 'HASH'
88 or $self->throw_exception("${remove_meth} needs an object");
90 my $rel_source = $self->search_related($rel)->result_source;
91 my $cond = $rel_source->relationship_info($f_rel)->{cond};
92 my $link_cond = $rel_source->resolve_condition(
95 $self->search_related($rel, $link_cond)->delete;