Merge the last bits of indirect callchain optimization
[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 1;
17
18 __END__
19
20 =head1 NAME
21
22 DBIx::Class::Relationship - Inter-table relationships
23
24 =head1 SYNOPSIS
25
26   ## Creating relationships
27   MyApp::Schema::Actor->has_many('actorroles' => 'MyApp::Schema::ActorRole',
28                                 'actor');
29   MyApp::Schema::Role->has_many('actorroles' => 'MyApp::Schema::ActorRole',
30                                 'role');
31   MyApp::Schema::ActorRole->belongs_to('role' => 'MyApp::Schema::Role');
32   MyApp::Schema::ActorRole->belongs_to('actor' => 'MyApp::Schema::Actor');
33
34   MyApp::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
35   MyApp::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
36
37   ## Using relationships
38   $schema->resultset('Actor')->find({ id => 1})->roles();
39   $schema->resultset('Role')->find({ id => 1 })->actorroles->search_related('actor', { Name => 'Fred' });
40   $schema->resultset('Actor')->add_to_roles({ Name => 'Sherlock Holmes'});
41
42 See L<DBIx::Class::Manual::Cookbook> for more.
43
44 =head1 DESCRIPTION
45
46 The word I<Relationship> has a specific meaning in DBIx::Class, see
47 the definition in the L<Glossary|DBIx::Class::Manual::Glossary/Relationship>.
48
49 This class provides methods to set up relationships between the tables
50 in your database model. Relationships are the most useful and powerful
51 technique that L<DBIx::Class> provides. To create efficient database queries,
52 create relationships between any and all tables that have something in
53 common, for example if you have a table Authors:
54
55   ID  | Name | Age
56  ------------------
57    1  | Fred | 30
58    2  | Joe  | 32
59
60 and a table Books:
61
62   ID  | Author | Name
63  --------------------
64    1  |      1 | Rulers of the universe
65    2  |      1 | Rulers of the galaxy
66
67 Then without relationships, the method of getting all books by Fred goes like
68 this:
69
70  my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
71  my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
72
73 With a has_many relationship called "books" on Author (see below for details),
74 we can do this instead:
75
76  my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
77
78 Each relationship sets up an accessor method on the
79 L<Result|DBIx::Class::Manual::Glossary/"Result"> objects that represent the items
80 of your table. From L<ResultSet|DBIx::Class::Manual::Glossary/"ResultSet"> objects,
81 the relationships can be searched using the "search_related" method.
82 In list context, each returns a list of Result objects for the related class,
83 in scalar context, a new ResultSet representing the joined tables is
84 returned. Thus, the calls can be chained to produce complex queries.
85 Since the database is not actually queried until you attempt to retrieve
86 the data for an actual item, no time is wasted producing them.
87
88  my $cheapfredbooks = $schema->resultset('Author')->find({
89    Name => 'Fred',
90  })->books->search_related('prices', {
91    Price => { '<=' => '5.00' },
92  });
93
94 will produce a query something like:
95
96  SELECT * FROM Author me
97  LEFT JOIN Books books ON books.author = me.id
98  LEFT JOIN Prices prices ON prices.book = books.id
99  WHERE prices.Price <= 5.00
100
101 all without needing multiple fetches.
102
103 Only the helper methods for setting up standard relationship types
104 are documented here. For the basic, lower-level methods, and a description
105 of all the useful *_related methods that you get for free, see
106 L<DBIx::Class::Relationship::Base>.
107
108 =head1 METHODS
109
110 All helper methods are called similar to the following template:
111
112   __PACKAGE__->$method_name('rel_name', 'Foreign::Class', \%cond|\@cond|\&cond?, \%attrs?);
113
114 Both C<cond> and C<attrs> are optional. Pass C<undef> for C<cond> if
115 you want to use the default value for it, but still want to set C<attrs>.
116
117 See L<DBIx::Class::Relationship::Base/condition> for full documentation on
118 definition of the C<cond> argument.
119
120 See L<DBIx::Class::Relationship::Base/attributes> for documentation on the
121 attributes that are allowed in the C<attrs> argument.
122
123
124 =head2 belongs_to
125
126 =over 4
127
128 =item Arguments: $accessor_name, $related_class, $our_fk_column|\%cond|\@cond|\$cond?, \%attrs?
129
130 =back
131
132 Creates a relationship where the calling class stores the foreign
133 class's primary key in one (or more) of the calling class columns.
134 This relationship defaults to using C<$accessor_name> as the column
135 name in this class to resolve the join against the primary key from
136 C<$related_class>, unless C<$our_fk_column> specifies the foreign key column
137 in this class or C<cond> specifies a reference to a join condition.
138
139 =over
140
141 =item accessor_name
142
143 This argument is the name of the method you can call on a
144 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
145 class matching this relationship. This is often called the
146 C<relation(ship) name>.
147
148 Use this accessor_name in L<DBIx::Class::ResultSet/join>
149 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
150 indicated by this relationship.
151
152 =item related_class
153
154 This is the class name of the table referenced by the foreign key in
155 this class.
156
157 =item our_fk_column
158
159 The column name on this class that contains the foreign key.
160
161 OR
162
163 =item cond
164
165 A hashref, arrayref or coderef specifying a custom join expression. For
166 more info see L<DBIx::Class::Relationship::Base/condition>.
167
168 =back
169
170   # in a Book class (where Author has many Books)
171   My::DBIC::Schema::Book->belongs_to(
172     author =>
173     'My::DBIC::Schema::Author',
174     'author_id'
175   );
176
177   # OR (same result)
178   My::DBIC::Schema::Book->belongs_to(
179     author =>
180     'My::DBIC::Schema::Author',
181     { 'foreign.author_id' => 'self.author_id' }
182   );
183
184   # OR (similar result but uglier accessor name)
185   My::DBIC::Schema::Book->belongs_to(
186     author_id =>
187     'My::DBIC::Schema::Author'
188   );
189
190   # Usage
191   my $author_obj = $book->author; # get author object
192   $book->author( $new_author_obj ); # set author object
193   $book->author_id(); # get the plain id
194
195   # To retrieve the plain id if you used the ugly version:
196   $book->get_column('author_id');
197
198 If some of the foreign key columns are
199 L<nullable|DBIx::Class::ResultSource/is_nullable> you probably want to set
200 the L<join_type|DBIx::Class::Relationship::Base/join_type> attribute to
201 C<left> explicitly so that SQL expressing this relation is composed with
202 a C<LEFT JOIN> (as opposed to C<INNER JOIN> which is default for
203 L</belongs_to> relationships). This ensures that relationship traversal
204 works consistently in all situations. (i.e. resultsets involving
205 L<join|DBIx::Class::ResultSet/join> or
206 L<prefetch|DBIx::Class::ResultSet/prefetch>).
207 The modified declaration is shown below:
208
209   # in a Book class (where Author has_many Books)
210   __PACKAGE__->belongs_to(
211     author =>
212     'My::DBIC::Schema::Author',
213     'author',
214     { join_type => 'left' }
215   );
216
217 Cascading deletes are off by default on a C<belongs_to>
218 relationship. To turn them on, pass C<< cascade_delete => 1 >>
219 in the $attr hashref.
220
221 By default, DBIC will return undef and avoid querying the database if a
222 C<belongs_to> accessor is called when any part of the foreign key IS NULL. To
223 disable this behavior, pass C<< undef_on_null_fk => 0 >> in the C<\%attrs>
224 hashref.
225
226 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
227 of C<has_a>.
228
229 See L<DBIx::Class::Relationship::Base/attributes> for documentation on relationship
230 methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
231 for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
232 which can be assigned to relationships as well.
233
234 =head2 has_many
235
236 =over 4
237
238 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
239
240 =back
241
242 Creates a one-to-many relationship where the foreign class refers to
243 this class's primary key. This relationship refers to zero or more
244 records in the foreign table (e.g. a C<LEFT JOIN>). This relationship
245 defaults to using the end of this classes namespace as the foreign key
246 in C<$related_class> to resolve the join, unless C<$their_fk_column>
247 specifies the foreign key column in C<$related_class> or C<cond>
248 specifies a reference to a join condition.
249
250 =over
251
252 =item accessor_name
253
254 This argument is the name of the method you can call on a
255 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve a resultset of the related
256 class restricted to the ones related to the result object. In list
257 context it returns the result objects. This is often called the
258 C<relation(ship) name>.
259
260 Use this accessor_name in L<DBIx::Class::ResultSet/join>
261 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
262 indicated by this relationship.
263
264 =item related_class
265
266 This is the class name of the table which contains a foreign key
267 column containing PK values of this class.
268
269 =item their_fk_column
270
271 The column name on the related class that contains the foreign key.
272
273 OR
274
275 =item cond
276
277 A hashref, arrayref  or coderef specifying a custom join expression. For
278 more info see L<DBIx::Class::Relationship::Base/condition>.
279
280 =back
281
282   # in an Author class (where Author has_many Books)
283   # assuming related class is storing our PK in "author_id"
284   My::DBIC::Schema::Author->has_many(
285     books =>
286     'My::DBIC::Schema::Book',
287     'author_id'
288   );
289
290   # OR (same result)
291   My::DBIC::Schema::Author->has_many(
292     books =>
293     'My::DBIC::Schema::Book',
294     { 'foreign.author_id' => 'self.id' },
295   );
296
297   # OR (similar result, assuming related_class is storing our PK, in "author")
298   # (the "author" is guessed at from "Author" in the class namespace)
299   My::DBIC::Schema::Author->has_many(
300     books =>
301     'My::DBIC::Schema::Book',
302   );
303
304
305   # Usage
306   # resultset of Books belonging to author
307   my $booklist = $author->books;
308
309   # resultset of Books belonging to author, restricted by author name
310   my $booklist = $author->books({
311     name => { LIKE => '%macaroni%' },
312     { prefetch => [qw/book/],
313   });
314
315   # array of Book objects belonging to author
316   my @book_objs = $author->books;
317
318   # force resultset even in list context
319   my $books_rs = $author->books;
320   ( $books_rs ) = $obj->books_rs;
321
322   # create a new book for this author, the relation fields are auto-filled
323   $author->create_related('books', \%col_data);
324   # alternative method for the above
325   $author->add_to_books(\%col_data);
326
327
328 Three methods are created when you create a has_many relationship.
329 The first method is the expected accessor method, C<$accessor_name()>.
330 The second is almost exactly the same as the accessor method but "_rs"
331 is added to the end of the method name, eg C<$accessor_name_rs()>.
332 This method works just like the normal accessor, except that it always
333 returns a resultset, even in list context. The third method, named C<<
334 add_to_$rel_name >>, will also be added to your Row items; this allows
335 you to insert new related items, using the same mechanism as in
336 L<DBIx::Class::Relationship::Base/"create_related">.
337
338 If you delete an object in a class with a C<has_many> relationship, all
339 the related objects will be deleted as well.  To turn this behaviour off,
340 pass C<< cascade_delete => 0 >> in the C<$attr> hashref.
341
342 The cascaded operations are performed after the requested delete or
343 update, so if your database has a constraint on the relationship, it
344 will have deleted/updated the related records or raised an exception
345 before DBIx::Class gets to perform the cascaded operation.
346
347 If you copy an object in a class with a C<has_many> relationship, all
348 the related objects will be copied as well. To turn this behaviour off,
349 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
350 defaults to C<< cascade_copy => 1 >>.
351
352 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
353 relationship methods and valid relationship attributes. Also see
354 L<DBIx::Class::ResultSet> for a L<list of standard resultset
355 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
356 relationships as well.
357
358 =head2 might_have
359
360 =over 4
361
362 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
363
364 =back
365
366 Creates an optional one-to-one relationship with a class. This relationship
367 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
368 resolve the join, unless C<$their_fk_column> specifies the foreign key
369 column in C<$related_class> or C<cond> specifies a reference to a join
370 condition.
371
372 =over
373
374 =item accessor_name
375
376 This argument is the name of the method you can call on a
377 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
378 class matching this relationship. This is often called the
379 C<relation(ship) name>.
380
381 Use this accessor_name in L<DBIx::Class::ResultSet/join>
382 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
383 indicated by this relationship.
384
385 =item related_class
386
387 This is the class name of the table which contains a foreign key
388 column containing PK values of this class.
389
390 =item their_fk_column
391
392 The column name on the related class that contains the foreign key.
393
394 OR
395
396 =item cond
397
398 A hashref, arrayref  or coderef specifying a custom join expression. For
399 more info see L<DBIx::Class::Relationship::Base/condition>.
400
401 =back
402
403   # Author may have an entry in the pseudonym table
404   My::DBIC::Schema::Author->might_have(
405     pseudonym =>
406     'My::DBIC::Schema::Pseudonym',
407     'author_id',
408   );
409
410   # OR (same result, assuming the related_class stores our PK)
411   My::DBIC::Schema::Author->might_have(
412     pseudonym =>
413     'My::DBIC::Schema::Pseudonym',
414   );
415
416   # OR (same result)
417   My::DBIC::Schema::Author->might_have(
418     pseudonym =>
419     'My::DBIC::Schema::Pseudonym',
420     { 'foreign.author_id' => 'self.id' },
421   );
422
423   # Usage
424   my $pname = $author->pseudonym; # to get the Pseudonym object
425
426 If you update or delete an object in a class with a C<might_have>
427 relationship, the related object will be updated or deleted as well. To
428 turn off this behavior, add C<< cascade_delete => 0 >> to the C<$attr>
429 hashref.
430
431 The cascaded operations are performed after the requested delete or
432 update, so if your database has a constraint on the relationship, it
433 will have deleted/updated the related records or raised an exception
434 before DBIx::Class gets to perform the cascaded operation.
435
436 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
437 relationship methods and valid relationship attributes. Also see
438 L<DBIx::Class::ResultSet> for a L<list of standard resultset
439 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
440 relationships as well.
441
442 Note that if you supply a condition on which to join, and the column in the
443 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
444 true value), than C<might_have> will warn about this because it's naughty and
445 you shouldn't do that. The warning will look something like:
446
447   "might_have/has_one" must not be on columns with is_nullable set to true (MySchema::SomeClass/key)
448
449 If you must be naughty, you can suppress the warning by setting
450 C<DBIC_DONT_VALIDATE_RELS> environment variable to a true value.  Otherwise,
451 you probably just meant to use C<DBIx::Class::Relationship/belongs_to>.
452
453 =head2 has_one
454
455 =over 4
456
457 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
458
459 =back
460
461 Creates a one-to-one relationship with a class. This relationship
462 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
463 resolve the join, unless C<$their_fk_column> specifies the foreign key
464 column in C<$related_class> or C<cond> specifies a reference to a join
465 condition.
466
467 =over
468
469 =item accessor_name
470
471 This argument is the name of the method you can call on a
472 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
473 class matching this relationship. This is often called the
474 C<relation(ship) name>.
475
476 Use this accessor_name in L<DBIx::Class::ResultSet/join>
477 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
478 indicated by this relationship.
479
480 =item related_class
481
482 This is the class name of the table which contains a foreign key
483 column containing PK values of this class.
484
485 =item their_fk_column
486
487 The column name on the related class that contains the foreign key.
488
489 OR
490
491 =item cond
492
493 A hashref, arrayref  or coderef specifying a custom join expression. For
494 more info see L<DBIx::Class::Relationship::Base/condition>.
495
496 =back
497
498   # Every book has exactly one ISBN
499   My::DBIC::Schema::Book->has_one(
500     isbn =>
501     'My::DBIC::Schema::ISBN',
502     'book_id',
503   );
504
505   # OR (same result, assuming related_class stores our PK)
506   My::DBIC::Schema::Book->has_one(
507     isbn =>
508     'My::DBIC::Schema::ISBN',
509   );
510
511   # OR (same result)
512   My::DBIC::Schema::Book->has_one(
513     isbn =>
514     'My::DBIC::Schema::ISBN',
515     { 'foreign.book_id' => 'self.id' },
516   );
517
518   # Usage
519   my $isbn_obj = $book->isbn; # to get the ISBN object
520
521 Creates a one-to-one relationship with another class. This is just
522 like C<might_have>, except the implication is that the other object is
523 always present. The only difference between C<has_one> and
524 C<might_have> is that C<has_one> uses an (ordinary) inner join,
525 whereas C<might_have> defaults to a left join.
526
527 The has_one relationship should be used when a row in the table must
528 have exactly one related row in another table. If the related row
529 might not exist in the foreign table, use the
530 L<DBIx::Class::Relationship/might_have> relationship.
531
532 In the above example, each Book in the database is associated with exactly one
533 ISBN object.
534
535 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
536 relationship methods and valid relationship attributes. Also see
537 L<DBIx::Class::ResultSet> for a L<list of standard resultset
538 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
539 relationships as well.
540
541 Note that if you supply a condition on which to join, if the column in the
542 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
543 true value), than warnings might apply just as with
544 L<DBIx::Class::Relationship/might_have>.
545
546 =head2 many_to_many
547
548 =over 4
549
550 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
551
552 =back
553
554 C<many_to_many> is a I<Relationship bridge> which has a specific
555 meaning in DBIx::Class, see the definition in the
556 L<Glossary|DBIx::Class::Manual::Glossary/Relationship bridge>.
557
558 C<many_to_many> is not strictly a relationship in its own right. Instead, it is
559 a bridge between two resultsets which provide the same kind of convenience
560 accessors as true relationships provide. Although the accessor will return a
561 resultset or collection of objects just like has_many does, you cannot call
562 C<related_resultset> and similar methods which operate on true relationships.
563
564 =over
565
566 =item accessor_name
567
568 This argument is the name of the method you can call on a
569 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the rows matching this
570 relationship.
571
572 On a many_to_many, unlike other relationships, this cannot be used in
573 L<DBIx::Class::ResultSet/search> to join tables. Use the relations
574 bridged across instead.
575
576 =item link_rel_name
577
578 This is the accessor_name from the has_many relationship we are
579 bridging from.
580
581 =item foreign_rel_name
582
583 This is the accessor_name of the belongs_to relationship in the link
584 table that we are bridging across (which gives us the table we are
585 bridging to).
586
587 =back
588
589 To create a many_to_many relationship from Actor to Role:
590
591   My::DBIC::Schema::Actor->has_many( actor_roles =>
592                                      'My::DBIC::Schema::ActorRoles',
593                                      'actor' );
594   My::DBIC::Schema::ActorRoles->belongs_to( role =>
595                                             'My::DBIC::Schema::Role' );
596   My::DBIC::Schema::ActorRoles->belongs_to( actor =>
597                                             'My::DBIC::Schema::Actor' );
598
599   My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
600                                          'role' );
601
602 And, for the reverse relationship, from Role to Actor:
603
604   My::DBIC::Schema::Role->has_many( actor_roles =>
605                                     'My::DBIC::Schema::ActorRoles',
606                                     'role' );
607
608   My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
609
610 To add a role for your actor, and fill in the year of the role in the
611 actor_roles table:
612
613   $actor->add_to_roles($role, { year => 1995 });
614
615 In the above example, ActorRoles is the link table class, and Role is the
616 foreign class. The C<$link_rel_name> parameter is the name of the accessor for
617 the has_many relationship from this table to the link table, and the
618 C<$foreign_rel_name> parameter is the accessor for the belongs_to relationship
619 from the link table to the foreign table.
620
621 To use many_to_many, existing relationships from the original table to the link
622 table, and from the link table to the end table must already exist, these
623 relation names are then used in the many_to_many call.
624
625 In the above example, the Actor class will have 3 many_to_many accessor methods
626 set: C<roles>, C<add_to_roles>, C<set_roles>, and similarly named accessors
627 will be created for the Role class for the C<actors> many_to_many
628 relationship.
629
630 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
631 relationship methods and valid relationship attributes. Also see
632 L<DBIx::Class::ResultSet> for a L<list of standard resultset
633 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
634 relationships as well.
635
636 =head1 FURTHER QUESTIONS?
637
638 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
639
640 =head1 COPYRIGHT AND LICENSE
641
642 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
643 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
644 redistribute it and/or modify it under the same terms as the
645 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.