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 for ($add_meth, $remove_meth, $set_meth, $rs_meth) {
28 warn "***************************************************************************\n".
29 "The many-to-many relationship $meth is trying to create a utility method called $_. This will overwrite the existing method on $class. You almost certainly want to rename your method or the many-to-many relationship, as your method will not be callable (it will use the one from the relationship instead.) YOU HAVE BEEN WARNED\n".
30 "***************************************************************************\n"
34 $rel_attrs->{alias} ||= $f_rel;
36 *{"${class}::${meth}_rs"} = sub {
38 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
39 my @args = ($f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs });
40 my $rs = $self->search_related($rel)->search_related(
41 $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
46 *{"${class}::${meth}"} = sub {
48 my $rs = $self->$rs_meth( @_ );
49 return (wantarray ? $rs->all : $rs);
52 *{"${class}::${add_meth}"} = sub {
54 @_ > 0 or $self->throw_exception(
55 "${add_meth} needs an object or hashref"
57 my $source = $self->result_source;
58 my $schema = $source->schema;
59 my $rel_source_name = $source->relationship_info($rel)->{source};
60 my $rel_source = $schema->resultset($rel_source_name)->result_source;
61 my $f_rel_source_name = $rel_source->relationship_info($f_rel)->{source};
62 my $f_rel_rs = $schema->resultset($f_rel_source_name)->search({}, $rel_attrs||{});
66 if (ref $_[0] eq 'HASH') {
67 $obj = $f_rel_rs->create($_[0]);
72 $obj = $f_rel_rs->create({@_});
75 my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
76 my $link = $self->search_related($rel)->new_result($link_vals);
77 $link->set_from_related($f_rel, $obj);
82 *{"${class}::${set_meth}"} = sub {
84 @_ > 0 or $self->throw_exception(
85 "{$set_meth} needs a list of objects or hashrefs"
87 my @to_set = (ref($_[0]) eq 'ARRAY' ? @{ $_[0] } : @_);
88 $self->search_related($rel, {})->delete;
89 $self->$add_meth($_) for (@to_set);
92 *{"${class}::${remove_meth}"} = sub {
94 @_ > 0 && ref $_[0] ne 'HASH'
95 or $self->throw_exception("${remove_meth} needs an object");
97 my $rel_source = $self->search_related($rel)->result_source;
98 my $cond = $rel_source->relationship_info($f_rel)->{cond};
99 my $link_cond = $rel_source->resolve_condition(
102 $self->search_related($rel, $link_cond)->delete;