8c8ceaa69cce9a165da25202d70d0a06ef42816a
[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   $class->ensure_class_loaded($f_class);
9   # no join condition or just a column name
10   if (!ref $cond) {
11     my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns };
12     $class->throw_exception("Can't infer join condition for ${rel} on ${class}; unable to load ${f_class}")
13       if $@;
14
15     my ($pri, $too_many) = keys %f_primaries;
16     $class->throw_exception("Can't infer join condition for ${rel} on ${class}; ${f_class} has no primary keys")
17       unless defined $pri;
18     $class->throw_exception("Can't infer join condition for ${rel} on ${class}; ${f_class} has multiple primary keys")
19       if $too_many;
20
21     my $fk = defined $cond ? $cond : $rel;
22     $class->throw_exception("Can't infer join condition for ${rel} on ${class}; $fk is not a column")
23       unless $class->has_column($fk);
24
25     my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
26     $class->add_relationship($rel, $f_class,
27       { "foreign.${pri}" => "self.${fk}" },
28       { accessor => $acc_type, %{$attrs || {}} }
29     );
30   }
31   # explicit join condition
32   elsif (ref $cond eq 'HASH') {
33     my $cond_rel;
34     for (keys %$cond) {
35       if (m/\./) { # Explicit join condition
36         $cond_rel = $cond;
37         last;
38       }
39       $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
40     }
41     my $acc_type = (keys %$cond_rel == 1 and $class->has_column($rel)) ? 'filter' : 'single';
42     $class->add_relationship($rel, $f_class,
43       $cond_rel,
44       { accessor => $acc_type, %{$attrs || {}} }
45     );
46   }
47   else {
48     $class->throw_exception('third argument for belongs_to must be undef, a column name, or a join condition');
49   }
50   return 1;
51 }
52
53 =head1 AUTHORS
54
55 Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
56
57 Matt S. Trout <mst@shadowcatsystems.co.uk>
58
59 =cut
60
61 1;