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}";
26 $rel_attrs->{alias} ||= $f_rel;
28 *{"${class}::${meth}"} = sub {
30 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
31 my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
32 $self->search_related($rel)->search_related(
33 $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
37 *{"${class}::${add_meth}"} = sub {
39 @_ > 0 or $self->throw_exception(
40 "${add_meth} needs an object or hashref"
42 my $source = $self->result_source;
43 my $schema = $source->schema;
44 my $rel_source_name = $source->relationship_info($rel)->{source};
45 my $rel_source = $schema->resultset($rel_source_name)->result_source;
46 my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
47 my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
51 if (ref $_[0] eq 'HASH') {
52 $obj = $f_rel_rs->create($_[0]);
57 $obj = $f_rel_rs->create({@_});
60 my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
61 my $link = $self->search_related($rel)->new_result({});
62 $link->set_from_related($f_rel, $obj);
63 $link->set_columns($link_vals);
67 *{"${class}::${set_meth}"} = sub {
69 @_ > 0 or $self->throw_exception(
70 "{$set_meth} needs a list of objects or hashrefs"
72 my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
73 $self->search_related($rel, {})->delete;
74 $self->$add_meth($_) for (@to_set);
77 *{"${class}::${remove_meth}"} = sub {
79 @_ > 0 && ref $_[0] ne 'HASH'
80 or $self->throw_exception("${remove_meth} needs an object");
82 my $rel_source = $self->search_related($rel)->result_source;
83 my $cond = $rel_source->relationship_info($f_rel)->{cond};
84 my $link_cond = $rel_source->resolve_condition(
87 $self->search_related($rel, $link_cond)->delete;