Documentation indenting/formatting fixes
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / Base.pm
CommitLineData
55e2d745 1package DBIx::Class::Relationship::Base;
2
3use strict;
4use warnings;
5
1edd1722 6use base qw/DBIx::Class/;
55e2d745 7
8__PACKAGE__->mk_classdata('_relationships', { } );
9
10=head1 NAME
11
8918977e 12DBIx::Class::Relationship::Base - Inter-table relationships
55e2d745 13
14=head1 SYNOPSIS
15
16=head1 DESCRIPTION
17
30236e47 18This class provides methods to describe the relationships between the
19tables in your database model. These are the "bare bones" relationships
20methods, for predefined ones, look in L<DBIx::Class::Relationship>.
55e2d745 21
22=head1 METHODS
23
8091aa91 24=head2 add_relationship
503536d5 25
30236e47 26=head3 Arguments: ('relname', 'Foreign::Class', $cond, $attrs)
27
503536d5 28 __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
29
30The condition needs to be an SQL::Abstract-style representation of the
30236e47 31join between the tables. When resolving the condition for use in a JOIN,
32keys using the psuedo-table I<foreign> are resolved to mean "the Table on the
33other side of the relationship", and values using the psuedo-table I<self>
34are resolved to mean "the Table this class is representing". Other
35restrictions, such as by value, sub-select and other tables, may also be
36used. Please check your database for JOIN parameter support.
37
38For example, if you're creating a rel from Author to Book, where the Book
39table has a column author_id containing the ID of the Author row:
503536d5 40
30236e47 41 { 'foreign.author_id' => 'self.id' }
503536d5 42
8091aa91 43will result in the JOIN clause
503536d5 44
30236e47 45 author me JOIN book book ON bar.author_id = me.id
503536d5 46
30236e47 47You can specify as many foreign => self mappings as necessary. Each key/value
48pair provided in a hashref will be used as ANDed conditions, to add an ORed
49condition, use an arrayref of hashrefs. See the L<SQL::Abstract> documentation
50for more details.
8091aa91 51
52Valid attributes are as follows:
53
54=over 4
55
56=item join_type
57
58Explicitly specifies the type of join to use in the relationship. Any SQL
59join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
60command immediately before C<JOIN>.
61
62=item proxy
63
30236e47 64An arrayref containing a list of accessors in the foreign class to create in
8091aa91 65the main class. If, for example, you do the following:
66
30236e47 67 MyDB::Schema::CD->might_have(liner_notes => 'MyDB::Schema::LinerNotes', undef, {
68 proxy => [ qw/notes/ ],
69 });
8091aa91 70
30236e47 71Then, assuming MyDB::Schema::LinerNotes has an accessor named notes, you can do:
8091aa91 72
30236e47 73 my $cd = MyDB::Schema::CD->find(1);
74 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
75 # created if it doesn't exist
8091aa91 76
77=item accessor
78
79Specifies the type of accessor that should be created for the relationship.
80Valid values are C<single> (for when there is only a single related object),
81C<multi> (when there can be many), and C<filter> (for when there is a single
82related object, but you also want the relationship accessor to double as
83a column accessor). For C<multi> accessors, an add_to_* method is also
84created, which calls C<create_related> for the relationship.
85
86=back
87
87c4e602 88=head2 register_relationship
89
90=head3 Arguments: ($relname, $rel_info)
71e65b39 91
30236e47 92Registers a relationship on the class. This is called internally by
93L<DBIx::Class::ResultSourceProxy> to set up Accessors and Proxies.
71e65b39 94
55e2d745 95=cut
96
71e65b39 97sub register_relationship { }
98
30236e47 99=head2 related_resultset($name)
100
101 $rs = $obj->related_resultset('related_table');
102
103Returns a L<DBIx::Class::ResultSet> for the relationship named $name.
104
105=cut
106
107sub related_resultset {
108 my $self = shift;
bc0c9800 109 $self->throw_exception("Can't call *_related as class methods")
110 unless ref $self;
30236e47 111 my $rel = shift;
112 my $rel_obj = $self->relationship_info($rel);
bc0c9800 113 $self->throw_exception( "No such relationship ${rel}" )
114 unless $rel_obj;
30236e47 115
116 return $self->{related_resultsets}{$rel} ||= do {
117 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
118 $attrs = { %{$rel_obj->{attrs} || {}}, %$attrs };
119
bc0c9800 120 $self->throw_exception( "Invalid query: @_" )
121 if (@_ > 1 && (@_ % 2 == 1));
30236e47 122 my $query = ((@_ > 1) ? {@_} : shift);
123
bc0c9800 124 my $cond = $self->result_source->resolve_condition(
125 $rel_obj->{cond}, $rel, $self
126 );
30236e47 127 if (ref $cond eq 'ARRAY') {
128 $cond = [ map { my $hash;
129 foreach my $key (keys %$_) {
130 my $newkey = $key =~ /\./ ? "me.$key" : $key;
131 $hash->{$newkey} = $_->{$key};
132 }; $hash } @$cond ];
133 } else {
134 foreach my $key (grep { ! /\./ } keys %$cond) {
135 $cond->{"me.$key"} = delete $cond->{$key};
136 }
137 }
138 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
bc0c9800 139 $self->result_source->related_source($rel)->resultset->search(
140 $query, $attrs
141 );
30236e47 142 };
143}
144
8091aa91 145=head2 search_related
503536d5 146
30236e47 147 $rs->search_related('relname', $cond, $attrs);
148
149Run a search on a related resultset. The search will be restricted to the
150item or items represented by the L<DBIx::Class::ResultSet> it was called
151upon. This method can be called on a ResultSet, a Row or a ResultSource class.
503536d5 152
153=cut
154
55e2d745 155sub search_related {
ff7bb7a1 156 return shift->related_resultset(shift)->search(@_);
b52e9bf8 157}
158
159=head2 count_related
160
7be93b07 161 $obj->count_related('relname', $cond, $attrs);
b52e9bf8 162
bc0c9800 163Returns the count of all the items in the related resultset, restricted by the
164current item or where conditions. Can be called on a
165L<DBIx::Classl::Manual::Glossary/"ResultSet"> or a
166L<DBIx::Class::Manual::Glossary/"Row"> object.
30236e47 167
b52e9bf8 168=cut
169
170sub count_related {
171 my $self = shift;
172 return $self->search_related(@_)->count;
55e2d745 173}
174
30236e47 175=head2 new_related
176
177 my $new_obj = $obj->new_related('relname', \%col_data);
178
179Create a new item of the related foreign class. If called on a
180L<DBIx::Class::Manual::Glossary/"Row"> object, it will magically
181set any primary key values into foreign key columns for you. The newly
182created item will not be saved into your storage until you call C<insert>
183on it.
184
185=cut
186
187sub new_related {
188 my ($self, $rel, $values, $attrs) = @_;
189 return $self->search_related($rel)->new($values, $attrs);
190}
191
8091aa91 192=head2 create_related
503536d5 193
30236e47 194 my $new_obj = $obj->create_related('relname', \%col_data);
195
196Creates a new item, similarly to new_related, and also inserts the item's data
197into your storage medium. See the distinction between C<create> and C<new>
198in L<DBIx::Class::ResultSet> for details.
503536d5 199
200=cut
201
55e2d745 202sub create_related {
3842b955 203 my $self = shift;
fea3d045 204 my $rel = shift;
64acc2bc 205 my $obj = $self->search_related($rel)->create(@_);
206 delete $self->{related_resultsets}->{$rel};
207 return $obj;
55e2d745 208}
209
8091aa91 210=head2 find_related
503536d5 211
30236e47 212 my $found_item = $obj->find_related('relname', @pri_vals | \%pri_vals);
213
214Attempt to find a related object using its primary key or unique constraints.
215See C<find> in L<DBIx::Class::ResultSet> for details.
503536d5 216
217=cut
218
1a14aa3f 219sub find_related {
220 my $self = shift;
221 my $rel = shift;
716b3d29 222 return $self->search_related($rel)->find(@_);
1a14aa3f 223}
224
8091aa91 225=head2 find_or_create_related
503536d5 226
30236e47 227 my $new_obj = $obj->find_or_create_related('relname', \%col_data);
228
229Find or create an item of a related class. See C<find_or_create> in
230L<DBIx::Class::ResultSet> for details.
503536d5 231
232=cut
233
55e2d745 234sub find_or_create_related {
235 my $self = shift;
1a14aa3f 236 return $self->find_related(@_) || $self->create_related(@_);
55e2d745 237}
238
8091aa91 239=head2 set_from_related
503536d5 240
30236e47 241 $book->set_from_related('author', $author_obj);
242
243Set column values on the current object, using related values from the given
244related object. This is used to associate previously separate objects, for
245example, to set the correct author for a book, find the Author object, then
246call set_from_related on the book.
247
248The columns are only set in the local copy of the object, call C<update> to set
249them in the storage.
503536d5 250
251=cut
252
55e2d745 253sub set_from_related {
254 my ($self, $rel, $f_obj) = @_;
4685e006 255 my $rel_obj = $self->relationship_info($rel);
701da8c4 256 $self->throw_exception( "No such relationship ${rel}" ) unless $rel_obj;
55e2d745 257 my $cond = $rel_obj->{cond};
bc0c9800 258 $self->throw_exception(
259 "set_from_related can only handle a hash condition; the ".
260 "condition for $rel is of type ".
261 (ref $cond ? ref $cond : 'plain scalar')
262 ) unless ref $cond eq 'HASH';
7fb16f1a 263 my $f_class = $self->result_source->schema->class($rel_obj->{class});
701da8c4 264 $self->throw_exception( "Object $f_obj isn't a ".$f_class )
55e2d745 265 unless $f_obj->isa($f_class);
fde6e28e 266 $self->set_columns(
267 $self->result_source->resolve_condition(
268 $rel_obj->{cond}, $f_obj, $rel));
55e2d745 269 return 1;
270}
271
8091aa91 272=head2 update_from_related
503536d5 273
30236e47 274 $book->update_from_related('author', $author_obj);
275
276As C<set_from_related>, but the changes are immediately updated onto your
277storage.
503536d5 278
279=cut
280
55e2d745 281sub update_from_related {
282 my $self = shift;
283 $self->set_from_related(@_);
284 $self->update;
285}
286
8091aa91 287=head2 delete_related
503536d5 288
30236e47 289 $obj->delete_related('relname', $cond, $attrs);
290
291Delete any related item subject to the given conditions.
503536d5 292
293=cut
294
55e2d745 295sub delete_related {
296 my $self = shift;
64acc2bc 297 my $obj = $self->search_related(@_)->delete;
298 delete $self->{related_resultsets}->{$_[0]};
299 return $obj;
55e2d745 300}
301
3021;
303
55e2d745 304=head1 AUTHORS
305
daec44b8 306Matt S. Trout <mst@shadowcatsystems.co.uk>
55e2d745 307
308=head1 LICENSE
309
310You may distribute this code under the same terms as Perl itself.
311
312=cut
313