throw exception for multi-has_many prefetch
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship.pm
1 package DBIx::Class::Relationship;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class/;
7
8 __PACKAGE__->load_own_components(qw/
9   Helpers
10   Accessor
11   CascadeActions
12   ProxyMethods
13   Base
14 /);
15
16 =head1 NAME
17
18 DBIx::Class::Relationship - Inter-table relationships
19
20 =head1 SYNOPSIS
21
22   MyDB::Schema::Actor->has_many('actorroles' => 'MyDB::Schema::ActorRole',
23                                 'actor');
24   MyDB::Schema::Role->has_many('actorroles' => 'MyDB::Schema::ActorRole',
25                                 'role');
26   MyDB::Schema::ActorRole->belongs_to('role' => 'MyDB::Schema::Role');
27   MyDB::Schema::ActorRole->belongs_to('actor' => 'MyDB::Schema::Actor');
28
29   MyDB::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
30   MyDB::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
31
32   $schema->resultset('Actor')->roles();
33   $schema->resultset('Role')->search_related('actors', { Name => 'Fred' });
34   $schema->resultset('ActorRole')->add_to_roles({ Name => 'Sherlock Holmes'});
35
36 See L<DBIx::Class::Manual::Cookbook> for more.
37
38 =head1 DESCRIPTION
39
40 This class provides methods to set up relationships between the tables
41 in your database model. Relationships are the most useful and powerful
42 technique that L<DBIx::Class> provides. To create efficient database queries,
43 create relationships between any and all tables that have something in
44 common, for example if you have a table Authors:
45
46   ID  | Name | Age
47  ------------------
48    1  | Fred | 30
49    2  | Joe  | 32
50
51 and a table Books:
52
53   ID  | Author | Name
54  --------------------
55    1  |      1 | Rulers of the universe
56    2  |      1 | Rulers of the galaxy
57
58 Then without relationships, the method of getting all books by Fred goes like
59 this:
60
61  my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
62  my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
63
64 With a has_many relationship called "books" on Author (see below for details),
65 we can do this instead:
66
67  my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
68
69 Each relationship sets up an accessor method on the
70 L<DBIx::Class::Manual::Glossary/"Row"> objects that represent the items
71 of your table. From L<DBIx::Class::Manual::Glossary/"ResultSet"> objects,
72 the relationships can be searched using the "search_related" method.
73 In list context, each returns a list of Row objects for the related class,
74 in scalar context, a new ResultSet representing the joined tables is
75 returned. Thus, the calls can be chained to produce complex queries.
76 Since the database is not actually queried until you attempt to retrieve
77 the data for an actual item, no time is wasted producing them.
78
79  my $cheapfredbooks = $schema->resultset('Author')->find({
80    Name => 'Fred',
81  })->books->search_related('prices', {
82    Price => { '<=' => '5.00' },
83  });
84
85 will produce a query something like:
86
87  SELECT * FROM Author me
88  LEFT JOIN Books books ON books.author = me.id
89  LEFT JOIN Prices prices ON prices.book = books.id
90  WHERE prices.Price <= 5.00
91
92 all without needing multiple fetches.
93
94 Only the helper methods for setting up standard relationship types
95 are documented here. For the basic, lower-level methods, and a description
96 of all the useful *_related methods that you get for free, see
97 L<DBIx::Class::Relationship::Base>.
98
99 =head1 METHODS
100
101 All helper methods are called similar to the following template:
102
103   __PACKAGE__->$method_name('relname', 'Foreign::Class', $cond, $attrs);
104   
105 Both C<$cond> and C<$attrs> are optional. Pass C<undef> for C<$cond> if
106 you want to use the default value for it, but still want to set C<$attrs>.
107
108 See L<DBIx::Class::Relationship::Base> for documentation on the
109 attrubutes that are allowed in the C<$attrs> argument.
110
111
112 =head2 belongs_to
113
114 =over 4
115
116 =item Arguments: $accessor_name, $related_class, $fk_column|$cond?, $attr?
117
118 =back
119
120 Creates a relationship where the calling class stores the foreign class's
121 primary key in one (or more) of its columns. This relationship defaults to
122 using C<$accessor_name> as the foreign key in C<$related_class> to resolve the
123 join, unless C<$fk_column> specifies the foreign key column in
124 this class or C<$cond> specifies a reference to a join condition hash.
125
126 =over
127
128 =item accessor_name
129
130 This argument is the name of the method you can call on a
131 L<DBIx::Class::Row> object to retrieve the instance of the foreign
132 class matching this relationship. This is often called the
133 C<relation(ship) name>.
134
135 Use this accessor_name in L<DBIx::Class::ResultSet/join>
136 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
137 indicated by this relationship.
138
139 =item related_class
140
141 This is the class name of the table referenced by the foreign key in
142 this class.
143
144 =item fk_column
145
146 The column name on this class that contains the foreign key.
147
148 OR
149
150 =item cond
151
152 A hashref where the keys are C<foreign.$column_on_related_table> and
153 the values are C<self.$foreign_key_column>. This is useful for
154 relations that are across multiple columns.
155
156 =back
157
158
159   # in a Book class (where Author has many Books)
160   My::DBIC::Schema::Book->belongs_to( author => 'My::DBIC::Schema::Author' );
161
162   my $author_obj = $obj->author; # get author object
163   $obj->author( $new_author_obj ); # set author object
164
165 The above belongs_to relationship could also have been specified as,
166
167   My::DBIC::Schema::Book->belongs_to( author,
168                                       'My::DBIC::Schema::Author',
169                                       { 'foreign.author' => 'self.author' } );
170
171 If the relationship is optional -- i.e. the column containing the foreign key
172 can be NULL -- then the belongs_to relationship does the right thing. Thus, in
173 the example above C<$obj-E<gt>author> would return C<undef>.  However in this
174 case you would probably want to set the C<join_type> attribute so that a C<LEFT
175 JOIN> is done, which makes complex resultsets involving C<join> or C<prefetch>
176 operations work correctly.  The modified declaration is shown below:
177
178   # in a Book class (where Author has_many Books)
179   __PACKAGE__->belongs_to(author => 'My::DBIC::Schema::Author',
180                           'author', {join_type => 'left'});
181
182
183 Cascading deletes are off by default on a C<belongs_to>
184 relationship. To turn them on, pass C<< cascade_delete => 1 >>
185 in the $attr hashref.
186
187 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
188 of C<has_a>.
189
190 See L<DBIx::Class::Relationship::Base> for documentation on relationship
191 methods and valid relationship attributes.
192
193 =head2 has_many
194
195 =over 4
196
197 =item Arguments: $accessor_name, $related_class, $foreign_key_column|$cond?, $attr?
198
199 =back
200
201 Creates a one-to-many relationship, where the corresponding elements of the
202 foreign class store the calling class's primary key in one (or more) of its
203 columns. This relationship defaults to using C<$accessor_name> as the foreign
204 key in C<$related_class> to resolve the join, unless C<$foreign_key_column>
205 specifies the foreign key column in C<$related_class> or C<$cond> specifies a
206 reference to a join condition hash.
207
208 =over
209
210 =item accessor_name
211
212 This argument is the name of the method you can call on a
213 L<DBIx::Class::Row> object to retrieve a resultset of the related
214 class restricted to the ones related to the row object. In list
215 context it returns the row objects.
216
217 Use this accessor_name (relation name) in L<DBIx::Class::ResultSet/join>
218 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
219 indicated by this relationship.
220
221 =item related_class
222
223 This is the class name of the table which contains a foreign key
224 column containing PK values of this class.
225
226 =item foreign_key_column
227
228 The column name on the related class that contains the foreign key.
229
230 OR
231
232 =item cond
233
234 A hashref where the keys are C<foreign.$column_on_related_table> and
235 the values are C<self.$foreign_key_column>. This is useful for
236 relations that are across multiple columns.
237
238 =back
239
240   # in an Author class (where Author has_many Books)
241   My::DBIC::Schema::Author->has_many(books => 'My::DBIC::Schema::Book', 'author');
242
243   my $booklist = $obj->books;
244   my $booklist = $obj->books({
245     name => { LIKE => '%macaroni%' },
246     { prefetch => [qw/book/],
247   });
248   my @book_objs = $obj->books;
249   my $books_rs = $obj->books;
250   ( $books_rs ) = $obj->books_rs;
251
252   $obj->add_to_books(\%col_data);
253
254 The above C<has_many> relationship could also have been specified with an
255 explicit join condition:
256
257   My::DBIC::Schema::Author->has_many( books => 'My::DBIC::Schema::Book', {
258     'foreign.author' => 'self.author',
259   });
260
261 Three methods are created when you create a has_many relationship.  The first
262 method is the expected accessor method, C<$accessor_name()>.  The second is
263 almost exactly the same as the accessor method but "_rs" is added to the end of
264 the method name.  This method works just like the normal accessor, except that
265 it returns a resultset no matter what, even in list context. The third method,
266 named C<< add_to_$relname >>, will also be added to your Row items; this
267 allows you to insert new related items, using the same mechanism as in
268 L<DBIx::Class::Relationship::Base/"create_related">.
269
270 If you delete an object in a class with a C<has_many> relationship, all
271 the related objects will be deleted as well.  To turn this behaviour off,
272 pass C<< cascade_delete => 0 >> in the C<$attr> hashref. However, any
273 database-level cascade or restrict will take precedence over a
274 DBIx-Class-based cascading delete.
275
276 If you copy an object in a class with a C<has_many> relationship, all
277 the related objects will be copied as well. To turn this behaviour off,
278 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
279 defaults to C<< cascade_copy => 1 >>.
280
281 See L<DBIx::Class::Relationship::Base> for documentation on relationship
282 methods and valid relationship attributes.
283
284 =head2 might_have
285
286 =over 4
287
288 =item Arguments: $accessor_name, $related_class, $foreign_key_column|$cond?, $attr?
289
290 =back
291
292 Creates an optional one-to-one relationship with a class. This relationship
293 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
294 resolve the join, unless C<$foreign_key_column> specifies the foreign key
295 column in C<$related_class> or C<$cond> specifies a reference to a join
296 condition hash.
297
298 =over
299
300 =item accessor_name
301
302 This argument is the name of the method you can call on a
303 L<DBIx::Class::Row> object to retrieve the instance of the foreign
304 class matching this relationship.
305
306 Use this accessor_name (relation name) in L<DBIx::Class::ResultSet/join>
307 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
308 indicated by this relationship.
309
310 =item related_class
311
312 This is the class name of the table which contains a foreign key
313 column containing PK values of this class.
314
315 =item foreign_key_column
316
317 The column name on the related class that contains the foreign key.
318
319 OR
320
321 =item cond
322
323 A hashref where the keys are C<foreign.$column_on_related_table> and
324 the values are C<self.$foreign_key_column>. This is useful for
325 relations that are across multiple columns.
326
327 =back
328
329   My::DBIC::Schema::Author->might_have( pseudonym =>
330                                         'My::DBIC::Schema::Pseudonym' );
331
332   my $pname = $obj->pseudonym; # to get the Pseudonym object
333
334 The above might_have relationship could have been specified as:
335
336   My::DBIC::Schema::Author->might_have( pseudonym =>
337                                         'My::DBIC::Schema::Pseudonym',
338                                         'author' );
339
340 Or even:
341
342   My::DBIC::Schema::Author->might_have( pseudonym =>
343                                         'My::DBIC::Schema::Pseudonym',
344                                         { 'foreign.author' => 'self.author' } );
345
346 If you update or delete an object in a class with a C<might_have>
347 relationship, the related object will be updated or deleted as well. To
348 turn off this behavior, add C<< cascade_delete => 0 >> to the C<$attr>
349 hashref. Any database-level update or delete constraints will override
350 this behavior.
351
352 See L<DBIx::Class::Relationship::Base> for documentation on relationship
353 methods and valid relationship attributes.
354
355 =head2 has_one
356
357 =over 4
358
359 =item Arguments: $accessor_name, $related_class_name, $join_condition?, $attr?
360
361 =back
362
363   My::DBIC::Schema::Book->has_one(isbn => 'My::DBIC::Schema::ISBN');
364
365   my $isbn_obj = $obj->isbn; # to get the ISBN object
366
367 Creates a one-to-one relationship with another class. This is just like
368 C<might_have>, except the implication is that the other object is always
369 present. The only difference between C<has_one> and C<might_have> is that
370 C<has_one> uses an (ordinary) inner join, whereas C<might_have> uses a
371 left join.
372
373 The has_one relationship should be used when a row in the table has exactly one
374 related row in another table. If the related row might not exist in the foreign
375 table, use the L<DBIx::Class::Relationship/might_have> relationship.
376
377 In the above example, each Book in the database is associated with exactly one
378 ISBN object.
379
380 See L<DBIx::Class::Relationship::Base> for documentation on relationship
381 methods and valid relationship attributes.
382
383 =head2 many_to_many
384
385 =over 4
386
387 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, $attr?
388
389 =back
390
391 C<many_to_many> is not strictly a relationship in its own right. Instead, it is
392 a bridge between two resultsets which provide the same kind of convenience
393 accessors as true relationships provide. Although the accessor will return a 
394 resultset or collection of objects just like has_many does, you cannot call 
395 C<related_resultset> and similar methods which operate on true relationships.
396
397 =over
398
399 =item accessor_name
400
401 This argument is the name of the method you can call on a
402 L<DBIx::Class::Row> object to retrieve the rows matching this
403 relationship.
404
405 On a many_to_many, unlike other relationships, this cannot be used in
406 L<DBIx::Class::ResultSet/search> to join tables. Use the relations
407 bridged across instead.
408
409 =item link_rel_name
410
411 This is the accessor_name from the has_many relationship we are
412 bridging from.
413
414 =item foreign_rel_name
415
416 This is the accessor_name of the belongs_to relationship in the link
417 table that we are bridging across (which gives us the table we are
418 bridging to).
419
420 =back
421
422 To create a many_to_many relationship from Actor to Role:
423
424   My::DBIC::Schema::Actor->has_many( actor_roles =>
425                                      'My::DBIC::Schema::ActorRoles',
426                                      'actor' );
427   My::DBIC::Schema::ActorRoles->belongs_to( role =>
428                                             'My::DBIC::Schema::Role' );
429   My::DBIC::Schema::ActorRoles->belongs_to( actor =>
430                                             'My::DBIC::Schema::Actor' );
431
432   My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
433                                          'role' );
434
435 And, for the reverse relationship, from Role to Actor:
436
437   My::DBIC::Schema::Role->has_many( actor_roles =>
438                                     'My::DBIC::Schema::ActorRoles',
439                                     'role' );
440
441   My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
442
443 To add a role for your actor, and fill in the year of the role in the
444 actor_roles table:
445
446   $actor->add_to_roles($role, { year => 1995 });
447
448 In the above example, ActorRoles is the link table class, and Role is the
449 foreign class. The C<$link_rel_name> parameter is the name of the accessor for
450 the has_many relationship from this table to the link table, and the
451 C<$foreign_rel_name> parameter is the accessor for the belongs_to relationship
452 from the link table to the foreign table.
453
454 To use many_to_many, existing relationships from the original table to the link
455 table, and from the link table to the end table must already exist, these
456 relation names are then used in the many_to_many call.
457
458 In the above example, the Actor class will have 3 many_to_many accessor methods
459 set: C<$roles>, C<$add_to_roles>, C<$set_roles>, and similarly named accessors
460 will be created for the Role class for the C<actors> many_to_many
461 relationship.
462
463 See L<DBIx::Class::Relationship::Base> for documentation on relationship
464 methods and valid relationship attributes.
465
466 =cut
467
468 1;
469
470 =head1 AUTHORS
471
472 Matt S. Trout <mst@shadowcatsystems.co.uk>
473
474 =head1 LICENSE
475
476 You may distribute this code under the same terms as Perl itself.
477
478 =cut
479