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