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