1 package # hide from PAUSE
2 DBIx::Class::Relationship::Accessor;
7 use Class::Inspector ();
9 sub register_relationship {
10 my ($class, $rel, $info) = @_;
11 if (my $acc_type = $info->{attrs}{accessor}) {
12 $class->add_relationship_accessor($rel => $acc_type);
14 $class->next::method($rel => $info);
17 sub add_relationship_accessor {
18 my ($class, $rel, $acc_type) = @_;
20 if ($acc_type eq 'single') {
21 my $rel_info = $class->relationship_info($rel);
25 $self->set_from_related($rel, @_);
26 return $self->{_relationship_data}{$rel} = $_[0];
27 } elsif (exists $self->{_relationship_data}{$rel}) {
28 return $self->{_relationship_data}{$rel};
30 my $cond = $self->result_source->_resolve_condition(
31 $rel_info->{cond}, $rel, $self
33 if ($rel_info->{attrs}->{undef_on_null_fk}){
34 return undef unless ref($cond) eq 'HASH';
35 return undef if grep { not defined $_ } values %$cond;
37 my $val = $self->find_related($rel, {}, {});
38 return $val unless $val; # $val instead of undef so that null-objects can go through
40 return $self->{_relationship_data}{$rel} = $val;
43 } elsif ($acc_type eq 'filter') {
44 $class->throw_exception("No such column $rel to filter")
45 unless $class->has_column($rel);
46 my $f_class = $class->relationship_info($rel)->{class};
47 $class->inflate_column($rel,
49 my ($val, $self) = @_;
50 return $self->find_or_new_related($rel, {}, {});
53 my ($val, $self) = @_;
54 $self->throw_exception("$val isn't a $f_class") unless $val->isa($f_class);
55 return ($val->_ident_values)[0];
56 # WARNING: probably breaks for multi-pri sometimes. FIXME
60 } elsif ($acc_type eq 'multi') {
61 $meth{$rel} = sub { shift->search_related($rel, @_) };
62 $meth{"${rel}_rs"} = sub { shift->search_related_rs($rel, @_) };
63 $meth{"add_to_${rel}"} = sub { shift->create_related($rel, @_); };
65 $class->throw_exception("No such relationship accessor type $acc_type");
69 no warnings 'redefine';
70 foreach my $meth (keys %meth) {
71 my $name = join '::', $class, $meth;
72 *$name = Sub::Name::subname($name, $meth{$meth});