Merge 'many_to_many' into 'DBIx-Class-current'
[dbsrgits/DBIx-Class.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) = @_;
c037c03a 17 $class->ensure_class_loaded($f_class);
99be059e 18 unless (ref $cond) {
103647d5 19 my ($pri, $too_many) = $class->primary_columns;
701da8c4 20 $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${class} has more" )
07037f89 21 if $too_many;
103647d5 22 my $f_class_loaded = eval { $f_class->columns };
8e04bf91 23 my ($f_key,$guess);
dcf8330b 24 if (defined $cond && length $cond) {
99be059e 25 $f_key = $cond;
dcf8330b 26 $guess = "caller specified foreign key '$f_key'";
103647d5 27 } elsif ($f_class_loaded && $f_class->has_column($rel)) {
07037f89 28 $f_key = $rel;
dcf8330b 29 $guess = "using given relationship '$rel' for foreign key";
07037f89 30 } else {
103647d5 31 ($f_key, $too_many) = $f_class->primary_columns;
701da8c4 32 $class->throw_exception( "might_have/has_one can only infer join for a single primary key; ${f_class} has more" )
07037f89 33 if $too_many;
dcf8330b 34 $guess = "using primary key of foreign class for foreign key";
22b15c96 35 }
701da8c4 36 $class->throw_exception("No such column ${f_key} on foreign class ${f_class} ($guess)")
103647d5 37 if $f_class_loaded && !$f_class->has_column($f_key);
503536d5 38 $cond = { "foreign.${f_key}" => "self.${pri}" };
07037f89 39 }
07037f89 40 $class->add_relationship($rel, $f_class,
41 $cond,
503536d5 42 { accessor => 'single',
07037f89 43 cascade_update => 1, cascade_delete => 1,
44 ($join_type ? ('join_type' => $join_type) : ()),
503536d5 45 %{$attrs || {}} });
07037f89 46 1;
22b15c96 47}
48
491;