backport the DBIx::Class::Storage::DBI::DESTROY fix for peopel sharing $dbh to other...
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / ManyToMany.pm
CommitLineData
75d07914 1package # hide from PAUSE
c0e7b4e5 2 DBIx::Class::Relationship::ManyToMany;
8973b6f1 3
4use strict;
5use warnings;
6
7sub many_to_many {
78af1010 8 my ($class, $meth, $rel, $f_rel, $rel_attrs) = @_;
8973b6f1 9 {
10 no strict 'refs';
11 no warnings 'redefine';
4b3ab474 12
b3f358b5 13 my $add_meth = "add_to_${meth}";
14 my $remove_meth = "remove_from_${meth}";
15 my $set_meth = "set_${meth}";
303cf522 16
78af1010 17 *{"${class}::${meth}"} = sub {
0f6ac8bb 18 my $self = shift;
19 my $attrs = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
3a868fb2 20 $self->search_related($rel)->search_related(
21 $f_rel, @_ > 0 ? @_ : undef, { %{$rel_attrs||{}}, %$attrs }
22 );
78af1010 23 };
4b3ab474 24
b3f358b5 25 *{"${class}::${add_meth}"} = sub {
303cf522 26 my $self = shift;
27 @_ > 0 or $self->throw_exception(
b3f358b5 28 "${add_meth} needs an object or hashref"
303cf522 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({@_}) );
3bd6e3e0 39 my $link_vals = @_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {};
303cf522 40 my $link = $self->search_related($rel)->new_result({});
41 $link->set_from_related($f_rel, $obj);
3bd6e3e0 42 $link->set_columns($link_vals);
303cf522 43 $link->insert();
4b3ab474 44 };
45
b3f358b5 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 {
303cf522 56 my $self = shift;
57 @_ > 0 && ref $_[0] ne 'HASH'
b3f358b5 58 or $self->throw_exception("${remove_meth} needs an object");
303cf522 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;
4b3ab474 66 };
67
8973b6f1 68 }
69}
70
711;