Added has_column and column_info methods
[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   my %f_primaries;
10   $f_primaries{$_} = 1 for eval { $f_class->primary_columns };
11   my $f_loaded = !$@;
12   # single key relationship
13   if (not defined $cond) {
14     $class->throw("Can't infer join condition for ${rel} on ${class}; unable to load ${f_class}") unless $f_loaded;
15     my ($pri, $too_many) = keys %f_primaries;
16     $class->throw("Can't infer join condition for ${rel} on ${class}; ${f_class} has multiple primary key") if $too_many;
17     my $acc_type = ($class->has_column($rel)) ? 'filter' : 'single';
18     $class->add_relationship($rel, $f_class,
19       { "foreign.${pri}" => "self.${rel}" },
20       { accessor => $acc_type, %{$attrs || {}} }
21     );
22   }
23   # multiple key relationship
24   else {
25     my $cond_rel;
26     for (keys %$cond) {
27       if (m/\./) { # Explicit join condition
28         $cond_rel = $cond;
29         last;
30       }
31       $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
32     }
33     $class->add_relationship($rel, $f_class,
34       $cond_rel,
35       { accessor => 'single', %{$attrs || {}} }
36     );
37   }
38   return 1;
39 }
40
41 =head1 AUTHORS
42
43 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
44
45 Matt S. Trout <mst@shadowcatsystems.co.uk>
46
47 =cut
48
49 1;