Clarification cascade_* attribute defaults documentation
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
CommitLineData
9b83fccd 1package # hide from PAUSE
2 DBIx::Class::Relationship::BelongsTo;
3
4# Documentation for these methods can be found in
5# DBIx::Class::Relationship
07037f89 6
7use strict;
8use warnings;
9
044e70c7 10our %_pod_inherit_config =
11 (
12 class_map => { 'DBIx::Class::Relationship::BelongsTo' => 'DBIx::Class::Relationship' }
13 );
14
07037f89 15sub belongs_to {
16 my ($class, $rel, $f_class, $cond, $attrs) = @_;
6bf6ba2f 17
18 # assume a foreign key contraint unless defined otherwise
19 $attrs->{is_foreign_key_constraint} = 1
20 if not exists $attrs->{is_foreign_key_constraint};
cef1bdda 21 $attrs->{undef_on_null_fk} = 1
22 if not exists $attrs->{undef_on_null_fk};
6bf6ba2f 23
aeb1bf75 24 # no join condition or just a column name
7b601771 25 if (!ref $cond) {
fd4df975 26 $class->ensure_class_loaded($f_class);
e8fb771b 27 my %f_primaries = map { $_ => 1 } eval { $f_class->_pri_cols };
fd4df975 28 $class->throw_exception(
e8fb771b 29 "Can't infer join condition for ${rel} on ${class}: $@"
fd4df975 30 ) if $@;
1e3bc087 31
32 my ($pri, $too_many) = keys %f_primaries;
fd4df975 33 $class->throw_exception(
34 "Can't infer join condition for ${rel} on ${class}; ".
fd4df975 35 "${f_class} has multiple primary keys"
36 ) if $too_many;
1e3bc087 37
38 my $fk = defined $cond ? $cond : $rel;
fd4df975 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);
1e3bc087 43
44 my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
07037f89 45 $class->add_relationship($rel, $f_class,
1e3bc087 46 { "foreign.${pri}" => "self.${fk}" },
5a3c5f64 47 { accessor => $acc_type, %{$attrs || {}} }
07037f89 48 );
49 }
aeb1bf75 50 # explicit join condition
4ff1b819 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->{$_};
99be059e 60 }
4ff1b819 61 $cond = $cond_rel;
07037f89 62 }
4ff1b819 63 my $acc_type = ((ref $cond eq 'HASH')
64 && keys %$cond == 1
65 && $class->has_column($rel))
66 ? 'filter'
67 : 'single';
07037f89 68 $class->add_relationship($rel, $f_class,
4ff1b819 69 $cond,
0cc03829 70 { accessor => $acc_type, %{$attrs || {}} }
07037f89 71 );
72 }
7b601771 73 else {
fd4df975 74 $class->throw_exception(
75 'third argument for belongs_to must be undef, a column name, '.
76 'or a join condition'
77 );
7b601771 78 }
07037f89 79 return 1;
80}
81
e09b8a14 82# Attempt to remove the POD so it (maybe) falls off the indexer
503536d5 83
e09b8a14 84#=head1 AUTHORS
85#
86#Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
87#
88#Matt S. Trout <mst@shadowcatsystems.co.uk>
89#
90#=cut
503536d5 91
07037f89 921;