1 package DBIx::Class::Relationship;
6 use base qw/DBIx::Class/;
8 __PACKAGE__->load_own_components(qw/
18 DBIx::Class::Relationship - Inter-table relationships
22 ## Creating relationships
23 MyApp::Schema::Actor->has_many('actorroles' => 'MyApp::Schema::ActorRole',
25 MyApp::Schema::Role->has_many('actorroles' => 'MyApp::Schema::ActorRole',
27 MyApp::Schema::ActorRole->belongs_to('role' => 'MyApp::Schema::Role');
28 MyApp::Schema::ActorRole->belongs_to('actor' => 'MyApp::Schema::Actor');
30 MyApp::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
31 MyApp::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
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'});
38 See L<DBIx::Class::Manual::Cookbook> for more.
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>.
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:
60 1 | 1 | Rulers of the universe
61 2 | 1 | Rulers of the galaxy
63 Then without relationships, the method of getting all books by Fred goes like
66 my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
67 my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
69 With a has_many relationship called "books" on Author (see below for details),
70 we can do this instead:
72 my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
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 Result 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.
84 my $cheapfredbooks = $schema->resultset('Author')->find({
86 })->books->search_related('prices', {
87 Price => { '<=' => '5.00' },
90 will produce a query something like:
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
97 all without needing multiple fetches.
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>.
106 All helper methods are called similar to the following template:
108 __PACKAGE__->$method_name('relname', 'Foreign::Class', \%cond|\@cond|\&cond?, \%attrs?);
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>.
113 See L<DBIx::Class::Relationship::Base/condition> for full documentation on
114 definition of the C<cond> argument.
116 See L<DBIx::Class::Relationship::Base/attributes> for documentation on the
117 attributes that are allowed in the C<attrs> argument.
124 =item Arguments: $accessor_name, $related_class, $our_fk_column|\%cond|\@cond|\$cond?, \%attrs?
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.
139 This argument is the name of the method you can call on a
140 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
141 class matching this relationship. This is often called the
142 C<relation(ship) name>.
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.
150 This is the class name of the table referenced by the foreign key in
155 The column name on this class that contains the foreign key.
161 A hashref, arrayref or coderef specifying a custom join expression. For
162 more info see L<DBIx::Class::Relationship::Base/condition>.
166 # in a Book class (where Author has many Books)
167 My::DBIC::Schema::Book->belongs_to(
169 'My::DBIC::Schema::Author',
174 My::DBIC::Schema::Book->belongs_to(
176 'My::DBIC::Schema::Author',
177 { 'foreign.author_id' => 'self.author_id' }
180 # OR (similar result but uglier accessor name)
181 My::DBIC::Schema::Book->belongs_to(
183 'My::DBIC::Schema::Author'
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
191 # To retrieve the plain id if you used the ugly version:
192 $book->get_column('author_id');
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:
204 # in a Book class (where Author has_many Books)
205 __PACKAGE__->belongs_to(
207 'My::DBIC::Schema::Author',
209 { join_type => 'left' }
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.
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>
222 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
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.
234 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
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.
250 This argument is the name of the method you can call on a
251 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve a resultset of the related
252 class restricted to the ones related to the result object. In list
253 context it returns the result objects. This is often called the
254 C<relation(ship) name>.
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.
262 This is the class name of the table which contains a foreign key
263 column containing PK values of this class.
265 =item their_fk_column
267 The column name on the related class that contains the foreign key.
273 A hashref, arrayref or coderef specifying a custom join expression. For
274 more info see L<DBIx::Class::Relationship::Base/condition>.
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(
282 'My::DBIC::Schema::Book',
287 My::DBIC::Schema::Author->has_many(
289 'My::DBIC::Schema::Book',
290 { 'foreign.author_id' => 'self.id' },
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(
297 'My::DBIC::Schema::Book',
302 # resultset of Books belonging to author
303 my $booklist = $author->books;
305 # resultset of Books belonging to author, restricted by author name
306 my $booklist = $author->books({
307 name => { LIKE => '%macaroni%' },
308 { prefetch => [qw/book/],
311 # array of Book objects belonging to author
312 my @book_objs = $author->books;
314 # force resultset even in list context
315 my $books_rs = $author->books;
316 ( $books_rs ) = $obj->books_rs;
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);
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">.
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.
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.
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 >>.
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.
358 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
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
372 This argument is the name of the method you can call on a
373 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
374 class matching this relationship. This is often called the
375 C<relation(ship) name>.
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.
383 This is the class name of the table which contains a foreign key
384 column containing PK values of this class.
386 =item their_fk_column
388 The column name on the related class that contains the foreign key.
394 A hashref, arrayref or coderef specifying a custom join expression. For
395 more info see L<DBIx::Class::Relationship::Base/condition>.
399 # Author may have an entry in the pseudonym table
400 My::DBIC::Schema::Author->might_have(
402 'My::DBIC::Schema::Pseudonym',
406 # OR (same result, assuming the related_class stores our PK)
407 My::DBIC::Schema::Author->might_have(
409 'My::DBIC::Schema::Pseudonym',
413 My::DBIC::Schema::Author->might_have(
415 'My::DBIC::Schema::Pseudonym',
416 { 'foreign.author_id' => 'self.id' },
420 my $pname = $author->pseudonym; # to get the Pseudonym object
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>
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.
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.
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:
443 "might_have/has_one" must not be on columns with is_nullable set to true (MySchema::SomeClass/key)
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>.
453 =item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
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
467 This argument is the name of the method you can call on a
468 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the instance of the foreign
469 class matching this relationship. This is often called the
470 C<relation(ship) name>.
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.
478 This is the class name of the table which contains a foreign key
479 column containing PK values of this class.
481 =item their_fk_column
483 The column name on the related class that contains the foreign key.
489 A hashref, arrayref or coderef specifying a custom join expression. For
490 more info see L<DBIx::Class::Relationship::Base/condition>.
494 # Every book has exactly one ISBN
495 My::DBIC::Schema::Book->has_one(
497 'My::DBIC::Schema::ISBN',
501 # OR (same result, assuming related_class stores our PK)
502 My::DBIC::Schema::Book->has_one(
504 'My::DBIC::Schema::ISBN',
508 My::DBIC::Schema::Book->has_one(
510 'My::DBIC::Schema::ISBN',
511 { 'foreign.book_id' => 'self.id' },
515 my $isbn_obj = $book->isbn; # to get the ISBN object
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.
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.
528 In the above example, each Book in the database is associated with exactly one
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.
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>.
546 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
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>.
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.
564 This argument is the name of the method you can call on a
565 L<Result|DBIx::Class::Manual::ResultClass> object to retrieve the rows matching this
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.
574 This is the accessor_name from the has_many relationship we are
577 =item foreign_rel_name
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
585 To create a many_to_many relationship from Actor to Role:
587 My::DBIC::Schema::Actor->has_many( actor_roles =>
588 'My::DBIC::Schema::ActorRoles',
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' );
595 My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
598 And, for the reverse relationship, from Role to Actor:
600 My::DBIC::Schema::Role->has_many( actor_roles =>
601 'My::DBIC::Schema::ActorRoles',
604 My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
606 To add a role for your actor, and fill in the year of the role in the
609 $actor->add_to_roles($role, { year => 1995 });
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.
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.
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
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.
636 =head1 AUTHOR AND CONTRIBUTORS
638 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
642 You may distribute this code under the same terms as Perl itself.