release 0.08123
[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 use Try::Tiny;
7 use namespace::clean;
8
9 our %_pod_inherit_config =
10   (
11    class_map => { 'DBIx::Class::Relationship::HasMany' => 'DBIx::Class::Relationship' }
12   );
13
14 sub has_many {
15   my ($class, $rel, $f_class, $cond, $attrs) = @_;
16
17   unless (ref $cond) {
18     $class->ensure_class_loaded($f_class);
19     my ($pri, $too_many) = try { $class->_pri_cols }
20       catch {
21         $class->throw_exception("Can't infer join condition for ${rel} on ${class}: $_");
22       };
23
24     $class->throw_exception(
25       "has_many can only infer join for a single primary key; ".
26       "${class} has more"
27     ) if $too_many;
28
29     $class->throw_exception(
30       "has_many needs a primary key to infer a join; ".
31       "${class} has none"
32     ) if !defined $pri && (!defined $cond || !length $cond);
33
34     my ($f_key,$guess);
35     if (defined $cond && length $cond) {
36       $f_key = $cond;
37       $guess = "caller specified foreign key '$f_key'";
38     } else {
39       $class =~ /([^\:]+)$/;
40       $f_key = lc $1; # go ahead and guess; best we can do
41       $guess = "using our class name '$class' as foreign key";
42     }
43
44     my $f_class_loaded = try { $f_class->columns };
45     $class->throw_exception(
46       "No such column ${f_key} on foreign class ${f_class} ($guess)"
47     ) if $f_class_loaded && !$f_class->has_column($f_key);
48
49     $cond = { "foreign.${f_key}" => "self.${pri}" };
50   }
51
52   $class->add_relationship($rel, $f_class, $cond, {
53     accessor => 'multi',
54     join_type => 'LEFT',
55     cascade_delete => 1,
56     cascade_copy => 1,
57     %{$attrs||{}}
58   });
59 }
60
61 1;