added ensure_class_loaded method to Componentized, which should fix problems with...
[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 primary key; ${class} has more" )
15       if $too_many;
16
17     my ($f_key,$guess);
18     if (defined $cond && length $cond) {
19       $f_key = $cond;
20       $guess = "caller specified foreign key '$f_key'";
21     } else {
22       $class =~ /([^\:]+)$/;
23       $f_key = lc $1; # go ahead and guess; best we can do
24       $guess = "using our class name '$class' as foreign key";
25     }
26
27     my $f_class_loaded = eval { $f_class->columns };
28     $class->throw_exception("No such column ${f_key} on foreign class ${f_class} ($guess)")
29       if $f_class_loaded && !$f_class->has_column($f_key);
30       
31     $cond = { "foreign.${f_key}" => "self.${pri}" };
32   }
33
34   $class->add_relationship($rel, $f_class, $cond,
35                             { accessor => 'multi',
36                               join_type => 'LEFT',
37                               cascade_delete => 1,
38                               cascade_copy => 1,
39                               %{$attrs||{}} } );
40 }
41
42 1;