rename option to undef_on_null_fk and make it default for belongs_to
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::BelongsTo;
3
4 # Documentation for these methods can be found in
5 # DBIx::Class::Relationship
6
7 use strict;
8 use warnings;
9
10 sub belongs_to {
11   my ($class, $rel, $f_class, $cond, $attrs) = @_;
12
13   # assume a foreign key contraint unless defined otherwise
14   $attrs->{is_foreign_key_constraint} = 1 
15     if not exists $attrs->{is_foreign_key_constraint};
16   $attrs->{undef_on_null_fk} = 1
17     if not exists $attrs->{undef_on_null_fk};
18
19   # no join condition or just a column name
20   if (!ref $cond) {
21     $class->ensure_class_loaded($f_class);
22     my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns };
23     $class->throw_exception(
24       "Can't infer join condition for ${rel} on ${class}; ".
25       "unable to load ${f_class}: $@"
26     ) if $@;
27
28     my ($pri, $too_many) = keys %f_primaries;
29     $class->throw_exception(
30       "Can't infer join condition for ${rel} on ${class}; ".
31       "${f_class} has no primary keys"
32     ) unless defined $pri;
33     $class->throw_exception(
34       "Can't infer join condition for ${rel} on ${class}; ".
35       "${f_class} has multiple primary keys"
36     ) if $too_many;
37
38     my $fk = defined $cond ? $cond : $rel;
39     $class->throw_exception(
40       "Can't infer join condition for ${rel} on ${class}; ".
41       "$fk is not a column of $class"
42     ) unless $class->has_column($fk);
43
44     my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
45     $class->add_relationship($rel, $f_class,
46       { "foreign.${pri}" => "self.${fk}" },
47       { accessor => $acc_type, %{$attrs || {}} }
48     );
49   }
50   # explicit join condition
51   elsif (ref $cond) {
52     if (ref $cond eq 'HASH') { # ARRAY is also valid
53       my $cond_rel;
54       for (keys %$cond) {
55         if (m/\./) { # Explicit join condition
56           $cond_rel = $cond;
57           last;
58         }
59         $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
60       }
61       $cond = $cond_rel;
62     }
63     my $acc_type = ((ref $cond eq 'HASH')
64                        && keys %$cond == 1
65                        && $class->has_column($rel))
66                      ? 'filter'
67                      : 'single';
68     $class->add_relationship($rel, $f_class,
69       $cond,
70       { accessor => $acc_type, %{$attrs || {}} }
71     );
72   }
73   else {
74     $class->throw_exception(
75       'third argument for belongs_to must be undef, a column name, '.
76       'or a join condition'
77     );
78   }
79   return 1;
80 }
81
82 =head1 AUTHORS
83
84 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
85
86 Matt S. Trout <mst@shadowcatsystems.co.uk>
87
88 =cut
89
90 1;