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