Initial work on getting POD coverage testing working
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / BelongsTo.pm
CommitLineData
07037f89 1package DBIx::Class::Relationship::BelongsTo;
2
3use strict;
4use warnings;
5
6sub belongs_to {
7 my ($class, $rel, $f_class, $cond, $attrs) = @_;
c037c03a 8 $class->ensure_class_loaded($f_class);
aeb1bf75 9 # no join condition or just a column name
7b601771 10 if (!ref $cond) {
aeb1bf75 11 my %f_primaries = map { $_ => 1 } eval { $f_class->primary_columns };
701da8c4 12 $class->throw_exception("Can't infer join condition for ${rel} on ${class}; unable to load ${f_class}")
aeb1bf75 13 if $@;
1e3bc087 14
15 my ($pri, $too_many) = keys %f_primaries;
701da8c4 16 $class->throw_exception("Can't infer join condition for ${rel} on ${class}; ${f_class} has no primary keys")
75d07914 17 unless defined $pri;
aeb1bf75 18 $class->throw_exception("Can't infer join condition for ${rel} on ${class}; ${f_class} has multiple primary keys")
75d07914 19 if $too_many;
1e3bc087 20
21 my $fk = defined $cond ? $cond : $rel;
701da8c4 22 $class->throw_exception("Can't infer join condition for ${rel} on ${class}; $fk is not a column")
1e3bc087 23 unless $class->has_column($fk);
24
25 my $acc_type = $class->has_column($rel) ? 'filter' : 'single';
07037f89 26 $class->add_relationship($rel, $f_class,
1e3bc087 27 { "foreign.${pri}" => "self.${fk}" },
5a3c5f64 28 { accessor => $acc_type, %{$attrs || {}} }
07037f89 29 );
30 }
aeb1bf75 31 # explicit join condition
7b601771 32 elsif (ref $cond eq 'HASH') {
07037f89 33 my $cond_rel;
34 for (keys %$cond) {
99be059e 35 if (m/\./) { # Explicit join condition
36 $cond_rel = $cond;
37 last;
38 }
07037f89 39 $cond_rel->{"foreign.$_"} = "self.".$cond->{$_};
07037f89 40 }
35c2ee73 41 my $acc_type = (keys %$cond_rel == 1 and $class->has_column($rel)) ? 'filter' : 'single';
07037f89 42 $class->add_relationship($rel, $f_class,
43 $cond_rel,
0cc03829 44 { accessor => $acc_type, %{$attrs || {}} }
07037f89 45 );
46 }
7b601771 47 else {
701da8c4 48 $class->throw_exception('third argument for belongs_to must be undef, a column name, or a join condition');
7b601771 49 }
07037f89 50 return 1;
51}
52
503536d5 53=head1 AUTHORS
54
55Alexander Hartmaier <Alexander.Hartmaier@t-systems.at>
56
57Matt S. Trout <mst@shadowcatsystems.co.uk>
58
59=cut
60
07037f89 611;