1 package DBIx::Class::Relationship;
6 use base qw/Class::Data::Inheritable/;
8 __PACKAGE__->mk_classdata('_relationships', { } );
10 sub add_relationship {
11 my ($class, $rel, $f_class, $cond, $attrs) = @_;
12 my %rels = %{ $class->_relationships };
13 $rels{$rel} = { class => $f_class,
16 $class->_relationships(\%rels);
20 my ($self, $attrs, $key) = @_;
21 my $action = $attrs->{_action} || '';
22 if ($action eq 'convert') {
23 unless ($key =~ s/^foreign\.//) {
24 die "Unable to convert relationship to WHERE clause: invalid key ${key}";
27 } elsif ($action eq 'join') {
28 my ($type, $field) = split(/\./, $key);
29 if ($attrs->{_aliases}{$type}) {
30 return join('.', $attrs->{_aliases}{$type}, $field);
32 die "Unable to resolve type ${type}: only have aliases for ".
33 join(', ', keys %{$attrs->{_aliases}{$type} || {}});
36 return $self->NEXT::ACTUAL::_cond_key($attrs, $key);
40 my ($self, $attrs, $key, $value) = @_;
41 my $action = $attrs->{_action} || '';
42 if ($action eq 'convert') {
43 unless ($value =~ s/^self\.//) {
44 die "Unable to convert relationship to WHERE clause: invalid value ${value}";
46 unless ($self->can($value)) {
47 die "Unable to convert relationship to WHERE clause: no such accessor ${value}";
49 push(@{$attrs->{bind}}, $self->get_column($value));
51 } elsif ($action eq 'join') {
52 my ($type, $field) = split(/\./, $value);
53 if ($attrs->{_aliases}{$type}) {
54 return join('.', $attrs->{_aliases}{$type}, $field);
56 die "Unable to resolve type ${type}: only have aliases for ".
57 join(', ', keys %{$attrs->{_aliases}{$type} || {}});
61 return $self->NEXT::ACTUAL::_cond_value($attrs, $key, $value)
68 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
69 $attrs = { %{ pop(@_) } };
71 my $rel_obj = $self->_relationships->{$rel};
72 die "No such relationship ${rel}" unless $rel;
73 $attrs = { %{$rel_obj->{attrs}}, %{$attrs || {}} };
76 die "Invalid query: @_" if (@_ > 1 && (@_ % 2 == 1));
77 my $query = ((@_ > 1) ? {@_} : shift);
78 $s_cond = $self->_cond_resolve($query, $attrs);
80 $attrs->{_action} = 'convert';
81 my ($cond) = $self->_cond_resolve($rel_obj->{cond}, $attrs);
82 $cond = "${s_cond} AND ${cond}" if $s_cond;
83 return $rel_obj->{class}->retrieve_from_sql($cond, @{$attrs->{bind} || {}});
87 my ($self, $rel, $values, $attrs) = @_;
88 die "Can't call create_related as class method" unless ref $self;
89 die "create_related needs a hash" unless (ref $values eq 'HASH');
90 my $rel_obj = $self->_relationships->{$rel};
91 die "No such relationship ${rel}" unless $rel;
92 die "Can't abstract implicit create for ${rel}, condition not a hash"
93 unless ref $rel_obj->{cond} eq 'HASH';
94 $attrs = { %{$rel_obj->{attrs}}, %{$attrs || {}}, _action => 'convert' };
95 my %fields = %$values;
96 while (my ($k, $v) = each %{$rel_obj->{cond}}) {
97 $self->_cond_value($attrs, $k => $v);
98 $fields{$self->_cond_key($attrs, $k)} = (@{delete $attrs->{bind}})[0];
100 return $rel_obj->{class}->create(\%fields);