Changed result_source to result_source_instance in strategic places
[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     $class->throw("Can't infer join condition for ${rel} on ${class}; unable to load ${f_class}")
20       unless $f_loaded;
21
22     my ($pri, $too_many) = keys %f_primaries;
23     $class->throw("Can't infer join condition for ${rel} on ${class}; ${f_class} has no primary keys")
24       unless defined $pri;      
25     $class->throw("Can't infer join condition for ${rel} on ${class}; ${f_class} has multiple primary key")
26       if $too_many;      
27
28     my $fk = defined $cond ? $cond : $rel;
29     $class->throw("Can't infer join condition for ${rel} on ${class}; $fk is not a column")
30       unless $class->has_column($fk);
31
32     my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
33     $class->add_relationship($rel, $f_class,
34       { "foreign.${pri}" => "self.${fk}" },
35       { accessor => $acc_type, %{$attrs || {}} }
36     );
37   }
38   # multiple key relationship
39   elsif (ref $cond eq 'HASH') {
40     my $cond_rel;
41     for (keys %$cond) {
42       if (m/\./) { # Explicit join condition
43         $cond_rel = $cond;
44         last;
45       }
46       $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
47     }
48     $class->add_relationship($rel, $f_class,
49       $cond_rel,
50       { accessor => 'single', %{$attrs || {}} }
51     );
52   }
53   else {
54     $class->throw('third argument for belongs_to must be undef, a column name, or a join condition');
55   }
56   return 1;
57 }
58
59 =head1 AUTHORS
60
61 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
62
63 Matt S. Trout <mst@shadowcatsystems.co.uk>
64
65 =cut
66
67 1;