belongs_to relationships are explicitly flagged by default, to aid the DBIC SQLT...
[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;
9
10sub belongs_to {
11 my ($class, $rel, $f_class, $cond, $attrs) = @_;
6bf6ba2f 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
aeb1bf75 17 # no join condition or just a column name
7b601771 18 if (!ref $cond) {
fd4df975 19 $class->ensure_class_loaded($f_class);
aeb1bf75 20 my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns };
fd4df975 21 $class->throw_exception(
22 "Can't infer join condition for ${rel} on ${class}; ".
23 "unable to load ${f_class}: $@"
24 ) if $@;
1e3bc087 25
26 my ($pri, $too_many) = keys %f_primaries;
fd4df975 27 $class->throw_exception(
28 "Can't infer join condition for ${rel} on ${class}; ".
29 "${f_class} has no primary keys"
30 ) unless defined $pri;
31 $class->throw_exception(
32 "Can't infer join condition for ${rel} on ${class}; ".
33 "${f_class} has multiple primary keys"
34 ) if $too_many;
1e3bc087 35
36 my $fk = defined $cond ? $cond : $rel;
fd4df975 37 $class->throw_exception(
38 "Can't infer join condition for ${rel} on ${class}; ".
39 "$fk is not a column of $class"
40 ) unless $class->has_column($fk);
1e3bc087 41
42 my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
07037f89 43 $class->add_relationship($rel, $f_class,
1e3bc087 44 { "foreign.${pri}" => "self.${fk}" },
5a3c5f64 45 { accessor => $acc_type, %{$attrs || {}} }
07037f89 46 );
47 }
aeb1bf75 48 # explicit join condition
4ff1b819 49 elsif (ref $cond) {
50 if (ref $cond eq 'HASH') { # ARRAY is also valid
51 my $cond_rel;
52 for (keys %$cond) {
53 if (m/\./) { # Explicit join condition
54 $cond_rel = $cond;
55 last;
56 }
57 $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
99be059e 58 }
4ff1b819 59 $cond = $cond_rel;
07037f89 60 }
4ff1b819 61 my $acc_type = ((ref $cond eq 'HASH')
62 && keys %$cond == 1
63 && $class->has_column($rel))
64 ? 'filter'
65 : 'single';
07037f89 66 $class->add_relationship($rel, $f_class,
4ff1b819 67 $cond,
0cc03829 68 { accessor => $acc_type, %{$attrs || {}} }
07037f89 69 );
70 }
7b601771 71 else {
fd4df975 72 $class->throw_exception(
73 'third argument for belongs_to must be undef, a column name, '.
74 'or a join condition'
75 );
7b601771 76 }
07037f89 77 return 1;
78}
79
503536d5 80=head1 AUTHORS
81
82Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
83
84Matt S. Trout <mst@shadowcatsystems.co.uk>
85
86=cut
87
07037f89 881;