Better linking in Relatiomship POD
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Relationship / HasOne.pm
CommitLineData
c0e7b4e5 1package # hide from PAUSE
2 DBIx::Class::Relationship::HasOne;
22b15c96 3
4use strict;
5use warnings;
6
07037f89 7sub might_have {
8 shift->_has_one('LEFT' => @_);
9}
10
22b15c96 11sub has_one {
e5d98edd 12 shift->_has_one(undef() => @_);
07037f89 13}
14
15sub _has_one {
503536d5 16 my ($class, $join_type, $rel, $f_class, $cond, $attrs) = @_;
99be059e 17 unless (ref $cond) {
fd4df975 18 $class->ensure_class_loaded($f_class);
103647d5 19 my ($pri, $too_many) = $class->primary_columns;
e36de82e 20
fd4df975 21 $class->throw_exception(
22 "might_have/has_one can only infer join for a single primary key; ".
23 "${class} has more"
24 ) if $too_many;
e36de82e 25
26 $class->throw_exception(
27 "might_have/has_one needs a primary key to infer a join; ".
28 "${class} has none"
29 ) if !defined $pri && (!defined $cond || !length $cond);
30
103647d5 31 my $f_class_loaded = eval { $f_class->columns };
8e04bf91 32 my ($f_key,$guess);
dcf8330b 33 if (defined $cond && length $cond) {
99be059e 34 $f_key = $cond;
dcf8330b 35 $guess = "caller specified foreign key '$f_key'";
103647d5 36 } elsif ($f_class_loaded && $f_class->has_column($rel)) {
07037f89 37 $f_key = $rel;
dcf8330b 38 $guess = "using given relationship '$rel' for foreign key";
07037f89 39 } else {
103647d5 40 ($f_key, $too_many) = $f_class->primary_columns;
fd4df975 41 $class->throw_exception(
42 "might_have/has_one can only infer join for a single primary key; ".
43 "${f_class} has more"
44 ) if $too_many;
dcf8330b 45 $guess = "using primary key of foreign class for foreign key";
22b15c96 46 }
fd4df975 47 $class->throw_exception(
48 "No such column ${f_key} on foreign class ${f_class} ($guess)"
49 ) if $f_class_loaded && !$f_class->has_column($f_key);
503536d5 50 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 51 }
07037f89 52 $class->add_relationship($rel, $f_class,
53 $cond,
503536d5 54 { accessor => 'single',
07037f89 55 cascade_update => 1, cascade_delete => 1,
56 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 57 %{$attrs || {}} });
07037f89 58 1;
22b15c96 59}
60
611;