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