1 package DBIx::Class::Relationship;
6 use base qw/DBIx::Class/;
8 __PACKAGE__->load_own_components(qw/
22 DBIx::Class::Relationship - Inter-table relationships
26 ## Creating relationships
27 MyApp::Schema::Actor->has_many('actorroles' => 'MyApp::Schema::ActorRole',
29 MyApp::Schema::Role->has_many('actorroles' => 'MyApp::Schema::ActorRole',
31 MyApp::Schema::ActorRole->belongs_to('role' => 'MyApp::Schema::Role');
32 MyApp::Schema::ActorRole->belongs_to('actor' => 'MyApp::Schema::Actor');
34 MyApp::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
35 MyApp::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
37 ## Using relationships
38 $schema->resultset('Actor')->find({ id => 1})->roles();
39 $schema->resultset('Role')->find({ id => 1 })->actorroles->search_related('actor', { Name => 'Fred' });
40 $schema->resultset('Actor')->add_to_roles({ Name => 'Sherlock Holmes'});
42 See L<DBIx::Class::Manual::Cookbook> for more.
46 The word I<Relationship> has a specific meaning in DBIx::Class, see
47 the definition in the L<Glossary|DBIx::Class::Manual::Glossary/Relationship>.
49 This class provides methods to set up relationships between the tables
50 in your database model. Relationships are the most useful and powerful
51 technique that L<DBIx::Class> provides. To create efficient database queries,
52 create relationships between any and all tables that have something in
53 common, for example if you have a table Authors:
64 1 | 1 | Rulers of the universe
65 2 | 1 | Rulers of the galaxy
67 Then without relationships, the method of getting all books by Fred goes like
70 my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
71 my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
73 With a has_many relationship called "books" on Author (see below for details),
74 we can do this instead:
76 my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
78 Each relationship sets up an accessor method on the
79 L<Result|DBIx::Class::Manual::Glossary/"Result"> objects that represent the items
80 of your table. From L<ResultSet|DBIx::Class::Manual::Glossary/"ResultSet"> objects,
81 the relationships can be searched using the "search_related" method.
82 In list context, each returns a list of Result objects for the related class,
83 in scalar context, a new ResultSet representing the joined tables is
84 returned. Thus, the calls can be chained to produce complex queries.
85 Since the database is not actually queried until you attempt to retrieve
86 the data for an actual item, no time is wasted producing them.
88 my $cheapfredbooks = $schema->resultset('Author')->find({
90 })->books->search_related('prices', {
91 Price => { '<=' => '5.00' },
94 will produce a query something like:
96 SELECT * FROM Author me
97 LEFT JOIN Books books ON books.author = me.id
98 LEFT JOIN Prices prices ON prices.book = books.id
99 WHERE prices.Price <= 5.00
101 all without needing multiple fetches.
103 Only the helper methods for setting up standard relationship types
104 are documented here. For the basic, lower-level methods, and a description
105 of all the useful *_related methods that you get for free, see
106 L<DBIx::Class::Relationship::Base>.
110 All helper methods are called similar to the following template:
112 __PACKAGE__->$method_name('rel_name', 'Foreign::Class', \%cond|\@cond|\&cond?, \%attrs?);
114 Both C<cond> and C<attrs> are optional. Pass C<undef> for C<cond> if
115 you want to use the default value for it, but still want to set C<attrs>.
117 See L<DBIx::Class::Relationship::Base/condition> for full documentation on
118 definition of the C<cond> argument.
120 See L<DBIx::Class::Relationship::Base/attributes> for documentation on the
121 attributes that are allowed in the C<attrs> argument.
128 =item Arguments: $accessor_name, $related_class, $our_fk_column|\%cond|\@cond|\$cond?, \%attrs?
132 Creates a relationship where the calling class stores the foreign
133 class's primary key in one (or more) of the calling class columns.
134 This relationship defaults to using C<$accessor_name> as the column
135 name in this class to resolve the join against the primary key from
136 C<$related_class>, unless C<$our_fk_column> specifies the foreign key column
137 in this class or C<cond> specifies a reference to a join condition.
143 This argument is the name of the method you can call on a
144 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
145 class matching this relationship. This is often called the
146 C<relation(ship) name>.
148 Use this accessor_name in L<DBIx::Class::ResultSet/join>
149 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
150 indicated by this relationship.
154 This is the class name of the table referenced by the foreign key in
159 The column name on this class that contains the foreign key.
165 A hashref, arrayref or coderef specifying a custom join expression. For
166 more info see L<DBIx::Class::Relationship::Base/condition>.
170 # in a Book class (where Author has many Books)
171 My::DBIC::Schema::Book->belongs_to(
173 'My::DBIC::Schema::Author',
178 My::DBIC::Schema::Book->belongs_to(
180 'My::DBIC::Schema::Author',
181 { 'foreign.author_id' => 'self.author_id' }
184 # OR (similar result but uglier accessor name)
185 My::DBIC::Schema::Book->belongs_to(
187 'My::DBIC::Schema::Author'
191 my $author_obj = $book->author; # get author object
192 $book->author( $new_author_obj ); # set author object
193 $book->author_id(); # get the plain id
195 # To retrieve the plain id if you used the ugly version:
196 $book->get_column('author_id');
198 If some of the foreign key columns are
199 L<nullable|DBIx::Class::ResultSource/is_nullable> you probably want to set
200 the L<join_type|DBIx::Class::Relationship::Base/join_type> attribute to
201 C<left> explicitly so that SQL expressing this relation is composed with
202 a C<LEFT JOIN> (as opposed to C<INNER JOIN> which is default for
203 L</belongs_to> relationships). This ensures that relationship traversal
204 works consistently in all situations. (i.e. resultsets involving
205 L<join|DBIx::Class::ResultSet/join> or
206 L<prefetch|DBIx::Class::ResultSet/prefetch>).
207 The modified declaration is shown below:
209 # in a Book class (where Author has_many Books)
210 __PACKAGE__->belongs_to(
212 'My::DBIC::Schema::Author',
214 { join_type => 'left' }
217 Cascading deletes are off by default on a C<belongs_to>
218 relationship. To turn them on, pass C<< cascade_delete => 1 >>
219 in the $attr hashref.
221 By default, DBIC will return undef and avoid querying the database if a
222 C<belongs_to> accessor is called when any part of the foreign key IS NULL. To
223 disable this behavior, pass C<< undef_on_null_fk => 0 >> in the C<\%attrs>
226 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
229 See L<DBIx::Class::Relationship::Base/attributes> for documentation on relationship
230 methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
231 for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
232 which can be assigned to relationships as well.
238 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
242 Creates a one-to-many relationship where the foreign class refers to
243 this class's primary key. This relationship refers to zero or more
244 records in the foreign table (e.g. a C<LEFT JOIN>). This relationship
245 defaults to using the end of this classes namespace as the foreign key
246 in C<$related_class> to resolve the join, unless C<$their_fk_column>
247 specifies the foreign key column in C<$related_class> or C<cond>
248 specifies a reference to a join condition.
254 This argument is the name of the method you can call on a
255 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve a resultset of the related
256 class restricted to the ones related to the result object. In list
257 context it returns the result objects. This is often called the
258 C<relation(ship) name>.
260 Use this accessor_name in L<DBIx::Class::ResultSet/join>
261 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
262 indicated by this relationship.
266 This is the class name of the table which contains a foreign key
267 column containing PK values of this class.
269 =item their_fk_column
271 The column name on the related class that contains the foreign key.
277 A hashref, arrayref or coderef specifying a custom join expression. For
278 more info see L<DBIx::Class::Relationship::Base/condition>.
282 # in an Author class (where Author has_many Books)
283 # assuming related class is storing our PK in "author_id"
284 My::DBIC::Schema::Author->has_many(
286 'My::DBIC::Schema::Book',
291 My::DBIC::Schema::Author->has_many(
293 'My::DBIC::Schema::Book',
294 { 'foreign.author_id' => 'self.id' },
297 # OR (similar result, assuming related_class is storing our PK, in "author")
298 # (the "author" is guessed at from "Author" in the class namespace)
299 My::DBIC::Schema::Author->has_many(
301 'My::DBIC::Schema::Book',
306 # resultset of Books belonging to author
307 my $booklist = $author->books;
309 # resultset of Books belonging to author, restricted by author name
310 my $booklist = $author->books({
311 name => { LIKE => '%macaroni%' },
312 { prefetch => [qw/book/],
315 # array of Book objects belonging to author
316 my @book_objs = $author->books;
318 # force resultset even in list context
319 my $books_rs = $author->books;
320 ( $books_rs ) = $obj->books_rs;
322 # create a new book for this author, the relation fields are auto-filled
323 $author->create_related('books', \%col_data);
324 # alternative method for the above
325 $author->add_to_books(\%col_data);
328 Three methods are created when you create a has_many relationship.
329 The first method is the expected accessor method, C<$accessor_name()>.
330 The second is almost exactly the same as the accessor method but "_rs"
331 is added to the end of the method name, eg C<$accessor_name_rs()>.
332 This method works just like the normal accessor, except that it always
333 returns a resultset, even in list context. The third method, named C<<
334 add_to_$rel_name >>, will also be added to your Row items; this allows
335 you to insert new related items, using the same mechanism as in
336 L<DBIx::Class::Relationship::Base/"create_related">.
338 If you delete an object in a class with a C<has_many> relationship, all
339 the related objects will be deleted as well. To turn this behaviour off,
340 pass C<< cascade_delete => 0 >> in the C<$attr> hashref.
342 The cascaded operations are performed after the requested delete or
343 update, so if your database has a constraint on the relationship, it
344 will have deleted/updated the related records or raised an exception
345 before DBIx::Class gets to perform the cascaded operation.
347 If you copy an object in a class with a C<has_many> relationship, all
348 the related objects will be copied as well. To turn this behaviour off,
349 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
350 defaults to C<< cascade_copy => 1 >>.
352 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
353 relationship methods and valid relationship attributes. Also see
354 L<DBIx::Class::ResultSet> for a L<list of standard resultset
355 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
356 relationships as well.
362 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
366 Creates an optional one-to-one relationship with a class. This relationship
367 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
368 resolve the join, unless C<$their_fk_column> specifies the foreign key
369 column in C<$related_class> or C<cond> specifies a reference to a join
376 This argument is the name of the method you can call on a
377 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
378 class matching this relationship. This is often called the
379 C<relation(ship) name>.
381 Use this accessor_name in L<DBIx::Class::ResultSet/join>
382 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
383 indicated by this relationship.
387 This is the class name of the table which contains a foreign key
388 column containing PK values of this class.
390 =item their_fk_column
392 The column name on the related class that contains the foreign key.
398 A hashref, arrayref or coderef specifying a custom join expression. For
399 more info see L<DBIx::Class::Relationship::Base/condition>.
403 # Author may have an entry in the pseudonym table
404 My::DBIC::Schema::Author->might_have(
406 'My::DBIC::Schema::Pseudonym',
410 # OR (same result, assuming the related_class stores our PK)
411 My::DBIC::Schema::Author->might_have(
413 'My::DBIC::Schema::Pseudonym',
417 My::DBIC::Schema::Author->might_have(
419 'My::DBIC::Schema::Pseudonym',
420 { 'foreign.author_id' => 'self.id' },
424 my $pname = $author->pseudonym; # to get the Pseudonym object
426 If you update or delete an object in a class with a C<might_have>
427 relationship, the related object will be updated or deleted as well. To
428 turn off this behavior, add C<< cascade_delete => 0 >> to the C<$attr>
431 The cascaded operations are performed after the requested delete or
432 update, so if your database has a constraint on the relationship, it
433 will have deleted/updated the related records or raised an exception
434 before DBIx::Class gets to perform the cascaded operation.
436 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
437 relationship methods and valid relationship attributes. Also see
438 L<DBIx::Class::ResultSet> for a L<list of standard resultset
439 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
440 relationships as well.
442 Note that if you supply a condition on which to join, and the column in the
443 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
444 true value), than C<might_have> will warn about this because it's naughty and
445 you shouldn't do that. The warning will look something like:
447 "might_have/has_one" must not be on columns with is_nullable set to true (MySchema::SomeClass/key)
449 If you must be naughty, you can suppress the warning by setting
450 C<DBIC_DONT_VALIDATE_RELS> environment variable to a true value. Otherwise,
451 you probably just meant to use C<DBIx::Class::Relationship/belongs_to>.
457 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
461 Creates a one-to-one relationship with a class. This relationship
462 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
463 resolve the join, unless C<$their_fk_column> specifies the foreign key
464 column in C<$related_class> or C<cond> specifies a reference to a join
471 This argument is the name of the method you can call on a
472 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
473 class matching this relationship. This is often called the
474 C<relation(ship) name>.
476 Use this accessor_name in L<DBIx::Class::ResultSet/join>
477 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
478 indicated by this relationship.
482 This is the class name of the table which contains a foreign key
483 column containing PK values of this class.
485 =item their_fk_column
487 The column name on the related class that contains the foreign key.
493 A hashref, arrayref or coderef specifying a custom join expression. For
494 more info see L<DBIx::Class::Relationship::Base/condition>.
498 # Every book has exactly one ISBN
499 My::DBIC::Schema::Book->has_one(
501 'My::DBIC::Schema::ISBN',
505 # OR (same result, assuming related_class stores our PK)
506 My::DBIC::Schema::Book->has_one(
508 'My::DBIC::Schema::ISBN',
512 My::DBIC::Schema::Book->has_one(
514 'My::DBIC::Schema::ISBN',
515 { 'foreign.book_id' => 'self.id' },
519 my $isbn_obj = $book->isbn; # to get the ISBN object
521 Creates a one-to-one relationship with another class. This is just
522 like C<might_have>, except the implication is that the other object is
523 always present. The only difference between C<has_one> and
524 C<might_have> is that C<has_one> uses an (ordinary) inner join,
525 whereas C<might_have> defaults to a left join.
527 The has_one relationship should be used when a row in the table must
528 have exactly one related row in another table. If the related row
529 might not exist in the foreign table, use the
530 L<DBIx::Class::Relationship/might_have> relationship.
532 In the above example, each Book in the database is associated with exactly one
535 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
536 relationship methods and valid relationship attributes. Also see
537 L<DBIx::Class::ResultSet> for a L<list of standard resultset
538 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
539 relationships as well.
541 Note that if you supply a condition on which to join, if the column in the
542 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
543 true value), than warnings might apply just as with
544 L<DBIx::Class::Relationship/might_have>.
550 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
554 C<many_to_many> is a I<Relationship bridge> which has a specific
555 meaning in DBIx::Class, see the definition in the
556 L<Glossary|DBIx::Class::Manual::Glossary/Relationship bridge>.
558 C<many_to_many> is not strictly a relationship in its own right. Instead, it is
559 a bridge between two resultsets which provide the same kind of convenience
560 accessors as true relationships provide. Although the accessor will return a
561 resultset or collection of objects just like has_many does, you cannot call
562 C<related_resultset> and similar methods which operate on true relationships.
568 This argument is the name of the method you can call on a
569 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the rows matching this
572 On a many_to_many, unlike other relationships, this cannot be used in
573 L<DBIx::Class::ResultSet/search> to join tables. Use the relations
574 bridged across instead.
578 This is the accessor_name from the has_many relationship we are
581 =item foreign_rel_name
583 This is the accessor_name of the belongs_to relationship in the link
584 table that we are bridging across (which gives us the table we are
589 To create a many_to_many relationship from Actor to Role:
591 My::DBIC::Schema::Actor->has_many( actor_roles =>
592 'My::DBIC::Schema::ActorRoles',
594 My::DBIC::Schema::ActorRoles->belongs_to( role =>
595 'My::DBIC::Schema::Role' );
596 My::DBIC::Schema::ActorRoles->belongs_to( actor =>
597 'My::DBIC::Schema::Actor' );
599 My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
602 And, for the reverse relationship, from Role to Actor:
604 My::DBIC::Schema::Role->has_many( actor_roles =>
605 'My::DBIC::Schema::ActorRoles',
608 My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
610 To add a role for your actor, and fill in the year of the role in the
613 $actor->add_to_roles($role, { year => 1995 });
615 In the above example, ActorRoles is the link table class, and Role is the
616 foreign class. The C<$link_rel_name> parameter is the name of the accessor for
617 the has_many relationship from this table to the link table, and the
618 C<$foreign_rel_name> parameter is the accessor for the belongs_to relationship
619 from the link table to the foreign table.
621 To use many_to_many, existing relationships from the original table to the link
622 table, and from the link table to the end table must already exist, these
623 relation names are then used in the many_to_many call.
625 In the above example, the Actor class will have 3 many_to_many accessor methods
626 set: C<roles>, C<add_to_roles>, C<set_roles>, and similarly named accessors
627 will be created for the Role class for the C<actors> many_to_many
630 See L<DBIx::Class::Relationship::Base/attributes> for documentation on
631 relationship methods and valid relationship attributes. Also see
632 L<DBIx::Class::ResultSet> for a L<list of standard resultset
633 attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
634 relationships as well.
636 =head1 FURTHER QUESTIONS?
638 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
640 =head1 COPYRIGHT AND LICENSE
642 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
643 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
644 redistribute it and/or modify it under the same terms as the
645 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.