release 0.08123
[dbsrgits/DBIx-Class.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;
ed7ab0f4 9use Try::Tiny;
fd323bf1 10use namespace::clean;
07037f89 11
fd323bf1 12our %_pod_inherit_config =
044e70c7 13 (
14 class_map => { 'DBIx::Class::Relationship::BelongsTo' => 'DBIx::Class::Relationship' }
15 );
16
07037f89 17sub belongs_to {
18 my ($class, $rel, $f_class, $cond, $attrs) = @_;
6bf6ba2f 19
20 # assume a foreign key contraint unless defined otherwise
fd323bf1 21 $attrs->{is_foreign_key_constraint} = 1
6bf6ba2f 22 if not exists $attrs->{is_foreign_key_constraint};
cef1bdda 23 $attrs->{undef_on_null_fk} = 1
24 if not exists $attrs->{undef_on_null_fk};
6bf6ba2f 25
aeb1bf75 26 # no join condition or just a column name
7b601771 27 if (!ref $cond) {
fd4df975 28 $class->ensure_class_loaded($f_class);
ed7ab0f4 29 my %f_primaries = map { $_ => 1 } try { $f_class->_pri_cols }
30 catch {
31 $class->throw_exception( "Can't infer join condition for ${rel} on ${class}: $_");
32 };
1e3bc087 33
34 my ($pri, $too_many) = keys %f_primaries;
fd4df975 35 $class->throw_exception(
36 "Can't infer join condition for ${rel} on ${class}; ".
fd4df975 37 "${f_class} has multiple primary keys"
38 ) if $too_many;
1e3bc087 39
40 my $fk = defined $cond ? $cond : $rel;
fd4df975 41 $class->throw_exception(
42 "Can't infer join condition for ${rel} on ${class}; ".
43 "$fk is not a column of $class"
44 ) unless $class->has_column($fk);
1e3bc087 45
46 my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
07037f89 47 $class->add_relationship($rel, $f_class,
1e3bc087 48 { "foreign.${pri}" => "self.${fk}" },
5a3c5f64 49 { accessor => $acc_type, %{$attrs || {}} }
07037f89 50 );
51 }
aeb1bf75 52 # explicit join condition
4ff1b819 53 elsif (ref $cond) {
54 if (ref $cond eq 'HASH') { # ARRAY is also valid
55 my $cond_rel;
56 for (keys %$cond) {
57 if (m/\./) { # Explicit join condition
58 $cond_rel = $cond;
59 last;
60 }
61 $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
99be059e 62 }
4ff1b819 63 $cond = $cond_rel;
07037f89 64 }
4ff1b819 65 my $acc_type = ((ref $cond eq 'HASH')
66 && keys %$cond == 1
67 && $class->has_column($rel))
68 ? 'filter'
69 : 'single';
07037f89 70 $class->add_relationship($rel, $f_class,
4ff1b819 71 $cond,
0cc03829 72 { accessor => $acc_type, %{$attrs || {}} }
07037f89 73 );
74 }
7b601771 75 else {
fd4df975 76 $class->throw_exception(
77 'third argument for belongs_to must be undef, a column name, '.
78 'or a join condition'
79 );
7b601771 80 }
07037f89 81 return 1;
82}
83
e09b8a14 84# Attempt to remove the POD so it (maybe) falls off the indexer
503536d5 85
e09b8a14 86#=head1 AUTHORS
87#
88#Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
89#
90#Matt S. Trout <mst@shadowcatsystems.co.uk>
91#
92#=cut
503536d5 93
07037f89 941;