272b01bb7656ef61aae3326354f09c27366f6891
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
1 package # hide from PAUSE
2     DBIx::Class::Relationship::BelongsTo;
3
4 # Documentation for these methods can be found in
5 # DBIx::Class::Relationship
6
7 use strict;
8 use warnings;
9
10 sub belongs_to {
11   my ($class, $rel, $f_class, $cond, $attrs) = @_;
12
13   # assume a foreign key contraint unless defined otherwise
14   $attrs->{is_foreign_key_constraint} = 1 
15     if not exists $attrs->{is_foreign_key_constraint};
16
17   # no join condition or just a column name
18   if (!ref $cond) {
19     $class->ensure_class_loaded($f_class);
20     my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns };
21     $class->throw_exception(
22       "Can't infer join condition for ${rel} on ${class}; ".
23       "unable to load ${f_class}: $@"
24     ) if $@;
25
26     my ($pri, $too_many) = keys %f_primaries;
27     $class->throw_exception(
28       "Can't infer join condition for ${rel} on ${class}; ".
29       "${f_class} has no primary keys"
30     ) unless defined $pri;
31     $class->throw_exception(
32       "Can't infer join condition for ${rel} on ${class}; ".
33       "${f_class} has multiple primary keys"
34     ) if $too_many;
35
36     my $fk = defined $cond ? $cond : $rel;
37     $class->throw_exception(
38       "Can't infer join condition for ${rel} on ${class}; ".
39       "$fk is not a column of $class"
40     ) unless $class->has_column($fk);
41
42     my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
43     $class->add_relationship($rel, $f_class,
44       { "foreign.${pri}" => "self.${fk}" },
45       { accessor => $acc_type, %{$attrs || {}} }
46     );
47   }
48   # explicit join condition
49   elsif (ref $cond) {
50     if (ref $cond eq 'HASH') { # ARRAY is also valid
51       my $cond_rel;
52       for (keys %$cond) {
53         if (m/\./) { # Explicit join condition
54           $cond_rel = $cond;
55           last;
56         }
57         $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
58       }
59       $cond = $cond_rel;
60     }
61     my $acc_type = ((ref $cond eq 'HASH')
62                        && keys %$cond == 1
63                        && $class->has_column($rel))
64                      ? 'filter'
65                      : 'single';
66     $class->add_relationship($rel, $f_class,
67       $cond,
68       { accessor => $acc_type, %{$attrs || {}} }
69     );
70   }
71   else {
72     $class->throw_exception(
73       'third argument for belongs_to must be undef, a column name, '.
74       'or a join condition'
75     );
76   }
77   return 1;
78 }
79
80 =head1 AUTHORS
81
82 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
83
84 Matt S. Trout <mst@shadowcatsystems.co.uk>
85
86 =cut
87
88 1;