9db06feb2dc7caee047ddc03c6f0e668f685be5e
[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 use Try::Tiny;
10 use namespace::clean;
11
12 our %_pod_inherit_config =
13   (
14    class_map => { 'DBIx::Class::Relationship::BelongsTo' => 'DBIx::Class::Relationship' }
15   );
16
17 sub belongs_to {
18   my ($class, $rel, $f_class, $cond, $attrs) = @_;
19
20   # assume a foreign key constraint unless defined otherwise
21   $attrs->{is_foreign_key_constraint} = 1
22     if not exists $attrs->{is_foreign_key_constraint};
23   $attrs->{undef_on_null_fk} = 1
24     if not exists $attrs->{undef_on_null_fk};
25
26   # no join condition or just a column name
27   if (!ref $cond) {
28     $class->ensure_class_loaded($f_class);
29     my %f_primaries = map { $_ => 1 } try { $f_class->result_source_instance->_pri_cols_or_die }
30       catch {
31         $class->throw_exception( "Can't infer join condition for '$rel' on ${class}: $_");
32       };
33
34     my ($pri, $too_many) = keys %f_primaries;
35     $class->throw_exception(
36       "Can't infer join condition for '$rel' on ${class}: "
37     . "${f_class} has multiple primary keys"
38     ) if $too_many;
39
40     my $fk = defined $cond ? $cond : $rel;
41     $class->throw_exception(
42       "Can't infer join condition for '$rel' on ${class}: "
43     . "'$fk' is not a column of $class"
44     ) unless $class->has_column($fk);
45
46     $cond = { "foreign.${pri}" => "self.${fk}" };
47
48   }
49   # explicit join condition
50   else {
51     if (ref $cond eq 'HASH') { # ARRAY is also valid
52       my $cond_rel;
53       for (keys %$cond) {
54         if (m/\./) { # Explicit join condition
55           $cond_rel = $cond;
56           last;
57         }
58         $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
59       }
60       $cond = $cond_rel;
61     }
62   }
63
64   my $acc_type = (
65     ref $cond eq 'HASH'
66       and
67     keys %$cond == 1
68       and
69     (keys %$cond)[0] =~ /^foreign\./
70       and
71     $class->has_column($rel)
72   ) ? 'filter' : 'single';
73
74   my $fk_columns = ($acc_type eq 'single' and ref $cond eq 'HASH')
75     ? { map { $_ =~ /^self\.(.+)/ ? ( $1 => 1 ) : () } (values %$cond ) }
76     : undef
77   ;
78
79   $class->add_relationship($rel, $f_class,
80     $cond,
81     {
82       accessor => $acc_type,
83       $fk_columns ? ( fk_columns => $fk_columns ) : (),
84       %{$attrs || {}}
85     }
86   );
87
88   return 1;
89 }
90
91 # Attempt to remove the POD so it (maybe) falls off the indexer
92
93 #=head1 AUTHORS
94 #
95 #Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
96 #
97 #Matt S. Trout <mst@shadowcatsystems.co.uk>
98 #
99 #=cut
100
101 1;