merge resultset branch through revision 371
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
CommitLineData
07037f89 1package DBIx::Class::Relationship::BelongsTo;
2
3use strict;
4use warnings;
5
6sub belongs_to {
7 my ($class, $rel, $f_class, $cond, $attrs) = @_;
8 eval "require $f_class";
bfab575a 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 = !$@;
bfab575a 16
07037f89 17 # single key relationship
bfab575a 18 if (!ref $cond) {
19 my ($pri,$too_many);
20 if (!defined $cond) {
21 $class->throw("Can't infer join condition for ${rel} on ${class}; unable to load ${f_class}") unless $f_loaded;
22 ($pri, $too_many) = keys %f_primaries;
23 $class->throw("Can't infer join condition for ${rel} on ${class}; ${f_class} has no primary keys") unless defined $pri;
24 $class->throw("Can't infer join condition for ${rel} on ${class}; ${f_class} has multiple primary key") if $too_many;
25 }
26 else {
27 $pri = $cond;
28 }
103647d5 29 my $acc_type = ($class->has_column($rel)) ? 'filter' : 'single';
07037f89 30 $class->add_relationship($rel, $f_class,
31 { "foreign.${pri}" => "self.${rel}" },
5a3c5f64 32 { accessor => $acc_type, %{$attrs || {}} }
07037f89 33 );
34 }
35 # multiple key relationship
bfab575a 36 elsif (ref $cond eq 'HASH') {
07037f89 37 my $cond_rel;
38 for (keys %$cond) {
99be059e 39 if (m/\./) { # Explicit join condition
40 $cond_rel = $cond;
41 last;
42 }
07037f89 43 $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
07037f89 44 }
07037f89 45 $class->add_relationship($rel, $f_class,
46 $cond_rel,
9a720616 47 { accessor => 'single', %{$attrs || {}} }
07037f89 48 );
49 }
bfab575a 50 else {
51 $class->throw('third argument for belongs_to must be undef, a column name, or a join condition');
52 }
07037f89 53 return 1;
54}
55
503536d5 56=head1 AUTHORS
57
58Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
59
60Matt S. Trout <mst@shadowcatsystems.co.uk>
61
62=cut
63
07037f89 641;