fixed new many_to_many accessors and added tests and docs
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasMany.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::HasMany;
3
4 use strict;
5 use warnings;
6
7 sub has_many {
8   my ($class, $rel, $f_class, $cond, $attrs) = @_;
9
10   $class->ensure_class_loaded($f_class);
11
12   unless (ref $cond) {
13     my ($pri, $too_many) = $class->primary_columns;
14     $class->throw_exception( "has_many can only infer join for a single ".
15                              "primary key; ${class} has more" )
16       if $too_many;
17
18     my ($f_key,$guess);
19     if (defined $cond && length $cond) {
20       $f_key = $cond;
21       $guess = "caller specified foreign key '$f_key'";
22     } else {
23       $class =~ /([^\:]+)$/;
24       $f_key = lc $1; # go ahead and guess; best we can do
25       $guess = "using our class name '$class' as foreign key";
26     }
27
28     my $f_class_loaded = eval { $f_class->columns };
29     $class->throw_exception(
30       "No such column ${f_key} on foreign class ${f_class} ($guess)"
31     ) if $f_class_loaded && !$f_class->has_column($f_key);
32       
33     $cond = { "foreign.${f_key}" => "self.${pri}" };
34   }
35
36   $class->add_relationship($rel, $f_class, $cond, {
37     accessor => 'multi',
38     join_type => 'LEFT',
39     cascade_delete => 1,
40     cascade_copy => 1,
41     %{$attrs||{}}
42   });
43 }
44
45 1;