1 package # hide from PAUSE
2 DBIx::Class::Relationship::ManyToMany;
8 my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
11 no warnings 'redefine';
13 my $add_meth = "add_to_${meth}";
14 my $remove_meth = "remove_from_${meth}";
15 my $set_meth = "set_${meth}";
17 $rel_attrs->{alias} ||= $f_rel;
19 *{"${class}::${meth}"} = sub {
21 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
22 my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
23 $self->search_related($rel)->search_related(
24 $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
28 *{"${class}::${add_meth}"} = sub {
30 @_ > 0 or $self->throw_exception(
31 "${add_meth} needs an object or hashref"
33 my $source = $self->result_source;
34 my $schema = $source->schema;
35 my $rel_source_name = $source->relationship_info($rel)->{source};
36 my $rel_source = $schema->resultset($rel_source_name)->result_source;
37 my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
38 my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
42 if (ref $_[0] eq 'HASH') {
43 $obj = $f_rel_rs->create($_[0]);
48 $obj = $f_rel_rs->create({@_});
51 my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
52 my $link = $self->search_related($rel)->new_result({});
53 $link->set_from_related($f_rel, $obj);
54 $link->set_columns($link_vals);
58 *{"${class}::${set_meth}"} = sub {
60 @_ > 0 or $self->throw_exception(
61 "{$set_meth} needs a list of objects or hashrefs"
63 my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
64 $self->search_related($rel, {})->delete;
65 $self->$add_meth($_) for (@to_set);
68 *{"${class}::${remove_meth}"} = sub {
70 @_ > 0 && ref $_[0] ne 'HASH'
71 or $self->throw_exception("${remove_meth} needs an object");
73 my $rel_source = $self->search_related($rel)->result_source;
74 my $cond = $rel_source->relationship_info($f_rel)->{cond};
75 my $link_cond = $rel_source->resolve_condition(
78 $self->search_related($rel, $link_cond)->delete;