release 0.08123
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / HasMany.pm
CommitLineData
75d07914 1package # hide from PAUSE
c0e7b4e5 2 DBIx::Class::Relationship::HasMany;
07037f89 3
4use strict;
5use warnings;
ed7ab0f4 6use Try::Tiny;
fd323bf1 7use namespace::clean;
07037f89 8
fd323bf1 9our %_pod_inherit_config =
044e70c7 10 (
11 class_map => { 'DBIx::Class::Relationship::HasMany' => 'DBIx::Class::Relationship' }
12 );
13
07037f89 14sub has_many {
15 my ($class, $rel, $f_class, $cond, $attrs) = @_;
c037c03a 16
dcf8330b 17 unless (ref $cond) {
fd4df975 18 $class->ensure_class_loaded($f_class);
fd323bf1 19 my ($pri, $too_many) = try { $class->_pri_cols }
ed7ab0f4 20 catch {
21 $class->throw_exception("Can't infer join condition for ${rel} on ${class}: $_");
22 };
fd4df975 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;
aeb1bf75 28
e36de82e 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
aeb1bf75 34 my ($f_key,$guess);
07037f89 35 if (defined $cond && length $cond) {
36 $f_key = $cond;
dcf8330b 37 $guess = "caller specified foreign key '$f_key'";
07037f89 38 } else {
39 $class =~ /([^\:]+)$/;
dcf8330b 40 $f_key = lc $1; # go ahead and guess; best we can do
41 $guess = "using our class name '$class' as foreign key";
07037f89 42 }
aeb1bf75 43
9780718f 44 my $f_class_loaded = try { $f_class->columns };
303cf522 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);
d4daee7b 48
8e04bf91 49 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 50 }
51
303cf522 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 });
07037f89 59}
60
611;