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