Commit | Line | Data |
9b83fccd |
1 | package # hide from PAUSE |
2 | DBIx::Class::Relationship::BelongsTo; |
3 | |
4 | # Documentation for these methods can be found in |
5 | # DBIx::Class::Relationship |
07037f89 |
6 | |
7 | use strict; |
8 | use warnings; |
9 | |
10 | sub belongs_to { |
11 | my ($class, $rel, $f_class, $cond, $attrs) = @_; |
aeb1bf75 |
12 | # no join condition or just a column name |
7b601771 |
13 | if (!ref $cond) { |
fd4df975 |
14 | $class->ensure_class_loaded($f_class); |
aeb1bf75 |
15 | my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns }; |
fd4df975 |
16 | $class->throw_exception( |
17 | "Can't infer join condition for ${rel} on ${class}; ". |
18 | "unable to load ${f_class}: $@" |
19 | ) if $@; |
1e3bc087 |
20 | |
21 | my ($pri, $too_many) = keys %f_primaries; |
fd4df975 |
22 | $class->throw_exception( |
23 | "Can't infer join condition for ${rel} on ${class}; ". |
24 | "${f_class} has no primary keys" |
25 | ) unless defined $pri; |
26 | $class->throw_exception( |
27 | "Can't infer join condition for ${rel} on ${class}; ". |
28 | "${f_class} has multiple primary keys" |
29 | ) if $too_many; |
1e3bc087 |
30 | |
31 | my $fk = defined $cond ? $cond : $rel; |
fd4df975 |
32 | $class->throw_exception( |
33 | "Can't infer join condition for ${rel} on ${class}; ". |
34 | "$fk is not a column of $class" |
35 | ) unless $class->has_column($fk); |
1e3bc087 |
36 | |
37 | my $acc_type = $class->has_column($rel) ? 'filter' : 'single'; |
07037f89 |
38 | $class->add_relationship($rel, $f_class, |
1e3bc087 |
39 | { "foreign.${pri}" => "self.${fk}" }, |
5a3c5f64 |
40 | { accessor => $acc_type, %{$attrs || {}} } |
07037f89 |
41 | ); |
42 | } |
aeb1bf75 |
43 | # explicit join condition |
7b601771 |
44 | elsif (ref $cond eq 'HASH') { |
07037f89 |
45 | my $cond_rel; |
46 | for (keys %$cond) { |
99be059e |
47 | if (m/\./) { # Explicit join condition |
48 | $cond_rel = $cond; |
49 | last; |
50 | } |
07037f89 |
51 | $cond_rel->{"foreign.$_"} = "self.".$cond->{$_}; |
07037f89 |
52 | } |
fd4df975 |
53 | my $acc_type = (keys %$cond_rel == 1 and $class->has_column($rel)) |
54 | ? 'filter' |
55 | : 'single'; |
07037f89 |
56 | $class->add_relationship($rel, $f_class, |
57 | $cond_rel, |
0cc03829 |
58 | { accessor => $acc_type, %{$attrs || {}} } |
07037f89 |
59 | ); |
60 | } |
7b601771 |
61 | else { |
fd4df975 |
62 | $class->throw_exception( |
63 | 'third argument for belongs_to must be undef, a column name, '. |
64 | 'or a join condition' |
65 | ); |
7b601771 |
66 | } |
07037f89 |
67 | return 1; |
68 | } |
69 | |
503536d5 |
70 | =head1 AUTHORS |
71 | |
72 | Alexander Hartmaier <Alexander.Hartmaier@t-systems.at> |
73 | |
74 | Matt S. Trout <mst@shadowcatsystems.co.uk> |
75 | |
76 | =cut |
77 | |
07037f89 |
78 | 1; |