1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 __PACKAGE__->mk_classdata('_relationships', { } );
12 DBIx::Class::Relationship::Base - Inter-table relationships
18 This class handles relationships between the tables in your database
19 model. It allows your to set up relationships, and to perform joins
24 =head2 add_relationship
26 __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
28 The condition needs to be an SQL::Abstract-style representation of the
29 join between the tables. For example, if you're creating a rel from Foo to Bar,
31 { 'foreign.foo_id' => 'self.id' }
33 will result in the JOIN clause
35 foo me JOIN bar bar ON bar.foo_id = me.id
37 You can specify as many foreign => self mappings as necessary.
39 Valid attributes are as follows:
45 Explicitly specifies the type of join to use in the relationship. Any SQL
46 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
47 command immediately before C<JOIN>.
51 An arrayref containing a list of accessors in the foreign class to proxy in
52 the main class. If, for example, you do the following:
54 __PACKAGE__->might_have(bar => 'Bar', undef, { proxy => qw[/ margle /] });
56 Then, assuming Bar has an accessor named margle, you can do:
58 my $obj = Foo->find(1);
59 $obj->margle(10); # set margle; Bar object is created if it doesn't exist
63 Specifies the type of accessor that should be created for the relationship.
64 Valid values are C<single> (for when there is only a single related object),
65 C<multi> (when there can be many), and C<filter> (for when there is a single
66 related object, but you also want the relationship accessor to double as
67 a column accessor). For C<multi> accessors, an add_to_* method is also
68 created, which calls C<create_related> for the relationship.
74 sub add_relationship {
75 shift->result_source->add_relationship(@_);
79 shift->result_source->relationships(@_);
82 sub relationship_info {
83 shift->result_source->relationship_info(@_);
86 sub resolve_condition {
87 my ($self, $cond, $attrs) = @_;
88 if (ref $cond eq 'HASH') {
90 foreach my $key (keys %$cond) {
91 my $val = $cond->{$key};
93 $self->throw("Can't handle this yet :(");
95 $ret{$self->_cond_key($attrs => $key)}
96 = $self->_cond_value($attrs => $key => $val);
101 $self->throw("Can't handle this yet :(");
106 my ($self, $attrs, $key, $alias) = @_;
107 my $action = $attrs->{_action} || '';
108 if ($action eq 'convert') {
109 unless ($key =~ s/^foreign\.//) {
110 $self->throw("Unable to convert relationship to WHERE clause: invalid key ${key}");
112 if (defined (my $alias = $attrs->{_aliases}{foreign})) {
113 return "${alias}.${key}";
117 } elsif ($action eq 'join') {
118 return $key unless $key =~ /\./;
119 my ($type, $field) = split(/\./, $key);
120 if (my $alias = $attrs->{_aliases}{$type}) {
121 my $class = $attrs->{_classes}{$alias};
122 $self->throw("Unknown column $field on $class as $alias")
123 unless $class->has_column($field);
124 return join('.', $alias, $field);
126 $self->throw( "Unable to resolve type ${type}: only have aliases for ".
127 join(', ', keys %{$attrs->{_aliases} || {}}) );
130 return $self->next::method($attrs, $key);
134 my ($self, $attrs, $key, $value) = @_;
135 my $action = $attrs->{_action} || '';
136 if ($action eq 'convert') {
137 unless ($value =~ s/^self\.//) {
138 $self->throw( "Unable to convert relationship to WHERE clause: invalid value ${value}" );
140 unless ($self->has_column($value)) {
141 $self->throw( "Unable to convert relationship to WHERE clause: no such accessor ${value}" );
143 return $self->get_column($value);
144 } elsif ($action eq 'join') {
145 return $key unless $key =~ /\./;
146 my ($type, $field) = split(/\./, $value);
147 if (my $alias = $attrs->{_aliases}{$type}) {
148 my $class = $attrs->{_classes}{$alias};
149 $self->throw("Unknown column $field on $class as $alias")
150 unless $class->has_column($field);
151 return join('.', $alias, $field);
153 $self->throw( "Unable to resolve type ${type}: only have aliases for ".
154 join(', ', keys %{$attrs->{_aliases} || {}}) );
158 return $self->next::method($attrs, $key, $value)
161 =head2 search_related
163 My::Table->search_related('relname', $cond, $attrs);
171 if (@_ > 1 && ref $_[$#_] eq 'HASH') {
172 $attrs = { %{ pop(@_) } };
174 my $rel_obj = $self->relationship_info($rel);
175 $self->throw( "No such relationship ${rel}" ) unless $rel_obj;
176 $attrs = { %{$rel_obj->{attrs} || {}}, %{$attrs || {}} };
178 $self->throw( "Invalid query: @_" ) if (@_ > 1 && (@_ % 2 == 1));
179 my $query = ((@_ > 1) ? {@_} : shift);
181 $attrs->{_action} = 'convert'; # shouldn't we resolve the cond to something
182 # to merge into the AST really?
183 my ($cond) = $self->resolve_condition($rel_obj->{cond}, $attrs);
184 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
185 #use Data::Dumper; warn Dumper($query);
186 #warn $rel_obj->{class}." $meth $cond ".join(', ', @{$attrs->{bind}||[]});
187 delete $attrs->{_action};
188 return $self->result_source->schema->resultset($rel_obj->{class}
189 )->search($query, $attrs);
194 My::Table->count_related('relname', $cond, $attrs);
200 return $self->search_related(@_)->count;
203 =head2 create_related
205 My::Table->create_related('relname', \%col_data);
212 return $class->search_related($rel)->create(@_);
217 My::Table->new_related('relname', \%col_data);
222 my ($self, $rel, $values, $attrs) = @_;
223 return $self->search_related($rel)->new($values, $attrs);
228 My::Table->find_related('relname', @pri_vals | \%pri_vals);
235 return $self->search_related($rel)->find(@_);
238 =head2 find_or_create_related
240 My::Table->find_or_create_related('relname', \%col_data);
244 sub find_or_create_related {
246 return $self->find_related(@_) || $self->create_related(@_);
249 =head2 set_from_related
251 My::Table->set_from_related('relname', $rel_obj);
255 sub set_from_related {
256 my ($self, $rel, $f_obj) = @_;
257 my $rel_obj = $self->relationship_info($rel);
258 $self->throw( "No such relationship ${rel}" ) unless $rel_obj;
259 my $cond = $rel_obj->{cond};
260 $self->throw( "set_from_related can only handle a hash condition; the "
261 ."condition for $rel is of type ".(ref $cond ? ref $cond : 'plain scalar'))
262 unless ref $cond eq 'HASH';
263 my $f_class = $self->result_source->schema->class($rel_obj->{class});
264 $self->throw( "Object $f_obj isn't a ".$f_class )
265 unless $f_obj->isa($f_class);
266 foreach my $key (keys %$cond) {
267 next if ref $cond->{$key}; # Skip literals and complex conditions
268 $self->throw("set_from_related can't handle $key as key")
269 unless $key =~ m/^foreign\.([^\.]+)$/;
270 my $val = $f_obj->get_column($1);
271 $self->throw("set_from_related can't handle ".$cond->{$key}." as value")
272 unless $cond->{$key} =~ m/^self\.([^\.]+)$/;
273 $self->set_column($1 => $val);
278 =head2 update_from_related
280 My::Table->update_from_related('relname', $rel_obj);
284 sub update_from_related {
286 $self->set_from_related(@_);
290 =head2 delete_related
292 My::Table->delete_related('relname', $cond, $attrs);
298 return $self->search_related(@_)->delete;
305 Matt S. Trout <mst@shadowcatsystems.co.uk>
309 You may distribute this code under the same terms as Perl itself.