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