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