- updated manifest and manifest.skip
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
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";
9   if ($@) {
10     $class->throw($@) unless $@ =~ /Can't locate/;
11   }
12
13   my %f_primaries;
14   $f_primaries{$_} = 1 for eval { $f_class->primary_columns };
15   my $f_loaded = !$@;
16   
17   # single key relationship
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     }
29     my $acc_type = ($class->has_column($rel)) ? 'filter' : 'single';
30     $class->add_relationship($rel, $f_class,
31       { "foreign.${pri}" => "self.${rel}" },
32       { accessor => $acc_type, %{$attrs || {}} }
33     );
34   }
35   # multiple key relationship
36   elsif (ref $cond eq 'HASH') {
37     my $cond_rel;
38     for (keys %$cond) {
39       if (m/\./) { # Explicit join condition
40         $cond_rel = $cond;
41         last;
42       }
43       $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
44     }
45     $class->add_relationship($rel, $f_class,
46       $cond_rel,
47       { accessor => 'single', %{$attrs || {}} }
48     );
49   }
50   else {
51     $class->throw('third argument for belongs_to must be undef, a column name, or a join condition');
52   }
53   return 1;
54 }
55
56 =head1 AUTHORS
57
58 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
59
60 Matt S. Trout <mst@shadowcatsystems.co.uk>
61
62 =cut
63
64 1;