Moved might_have compat back out into a CDBICompat class and documented stuff
[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   # single key relationship
10   if (not defined $cond) {
11     my ($pri, $too_many) = keys %{ $f_class->_primaries };
12     my $acc_type = ($class->_columns->{$rel}) ? 'filter' : 'single';
13     $class->add_relationship($rel, $f_class,
14       { "foreign.${pri}" => "self.${rel}" },
15       { accessor => $acc_type }
16     );
17   }
18   # multiple key relationship
19   else {
20     my %f_primaries = %{ $f_class->_primaries };
21     my $cond_rel;
22     for (keys %$cond) {
23       $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
24       # primary key usage checks
25       if (exists $f_primaries{$_}) {
26         delete $f_primaries{$_};
27       }
28       else
29       {
30         $class->throw("non primary key used in join condition: $_");
31       }
32     }
33     $class->throw("not all primary keys used in multi key relationship!") if keys %f_primaries;
34     $class->add_relationship($rel, $f_class,
35       $cond_rel,
36       { accessor => 'single', %{$attrs ||{}} }
37     );
38   }
39   return 1;
40 }
41
42 =head1 AUTHORS
43
44 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
45
46 Matt S. Trout <mst@shadowcatsystems.co.uk>
47
48 =cut
49
50 1;