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 MyDB::Schema::Actor->has_many('actorroles' => 'MyDB::Schema::ActorRole',
25 MyDB::Schema::Role->has_many('actorroles' => 'MyDB::Schema::ActorRole',
27 MyDB::Schema::ActorRole->belongs_to('role' => 'MyDB::Schema::Role');
28 MyDB::Schema::ActorRole->belongs_to('actor' => 'MyDB::Schema::Actor');
30 MyDB::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
31 MyDB::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
33 ## Using relationships
34 $schema->resultset('Actor')->roles();
35 $schema->resultset('Role')->search_related('actors', { Name => 'Fred' });
36 $schema->resultset('ActorRole')->add_to_roles({ Name => 'Sherlock Holmes'});
38 See L<DBIx::Class::Manual::Cookbook> for more.
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:
57 1 | 1 | Rulers of the universe
58 2 | 1 | Rulers of the galaxy
60 Then without relationships, the method of getting all books by Fred goes like
63 my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
64 my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
66 With a has_many relationship called "books" on Author (see below for details),
67 we can do this instead:
69 my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
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.
81 my $cheapfredbooks = $schema->resultset('Author')->find({
83 })->books->search_related('prices', {
84 Price => { '<=' => '5.00' },
87 will produce a query something like:
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
94 all without needing multiple fetches.
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>.
103 All helper methods are called similar to the following template:
105 __PACKAGE__->$method_name('relname', 'Foreign::Class', $cond, $attrs);
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>.
110 See L<DBIx::Class::Relationship::Base> for documentation on the
111 attrubutes that are allowed in the C<$attrs> argument.
118 =item Arguments: $accessor_name, $related_class, $fk_column|\%cond|\@cond?, \%attr?
122 Creates a relationship where the calling class stores the foreign
123 class's primary key in one (or more) of its columns. This relationship
124 defaults to using C<$accessor_name> as the column in this class
125 to resolve the join against the primary key from C<$related_class>,
126 unless C<$fk_column> specifies the foreign key column in this class or
127 C<cond> specifies a reference to a join condition hash.
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>.
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.
144 This is the class name of the table referenced by the foreign key in
149 The column name on this class that contains the foreign key.
155 A hashref where the keys are C<foreign.$column_on_related_table> and
156 the values are C<self.$foreign_key_column>. This is useful for
157 relations that are across multiple columns.
162 # in a Book class (where Author has many Books)
163 My::DBIC::Schema::Book->belongs_to(
165 'My::DBIC::Schema::Author',
170 My::DBIC::Schema::Book->belongs_to(
172 'My::DBIC::Schema::Author',
173 { 'foreign.author_id' => 'self.author_id' }
176 # OR (similar result but uglier accessor name)
177 My::DBIC::Schema::Book->belongs_to(
179 'My::DBIC::Schema::Author'
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
187 # To retrieve the plain id if you used the ugly version:
188 $book->get_column('author_id');
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:
198 # in a Book class (where Author has_many Books)
199 __PACKAGE__->belongs_to(
201 'My::DBIC::Schema::Author',
203 { join_type => 'left' }
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.
211 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
214 See L<DBIx::Class::Relationship::Base> for documentation on relationship
215 methods and valid relationship attributes.
221 =item Arguments: $accessor_name, $related_class, $foreign_key_column|\%cond|\@cond?, \%attr?
225 Creates a one-to-many relationship, where the corresponding elements of the
226 foreign class store the calling class's primary key in one (or more) of its
227 columns. This relationship defaults to using C<$accessor_name> as the foreign
228 key in C<$related_class> to resolve the join, unless C<$foreign_key_column>
229 specifies the foreign key column in C<$related_class> or C<cond> specifies a
230 reference to a join condition hash.
236 This argument is the name of the method you can call on a
237 L<DBIx::Class::Row> object to retrieve a resultset of the related
238 class restricted to the ones related to the row object. In list
239 context it returns the row objects. This is often called the
240 C<relation(ship) name>.
242 Use this accessor_name in L<DBIx::Class::ResultSet/join>
243 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
244 indicated by this relationship.
248 This is the class name of the table which contains a foreign key
249 column containing PK values of this class.
251 =item foreign_key_column
253 The column name on the related class that contains the foreign key.
259 A hashref where the keys are C<foreign.$foreign_key_column> and
260 the values are C<self.$matching_column>. This is useful for
261 relations that are across multiple columns.
265 An arrayref containing an SQL::Abstract-like condition. For example a
266 link table where two columns link back to the same table. This is an
269 My::Schema::Item->has_many('rels', 'My::Schema::Relationships',
270 [ { 'foreign.LItemID' => 'self.ID' },
271 { 'foreign.RItemID' => 'self.ID'} ]);
275 # in an Author class (where Author has_many Books)
276 My::DBIC::Schema::Author->has_many(
278 'My::DBIC::Schema::Book',
282 # OR (same result, assuming related_class is storing our PK)
283 My::DBIC::Schema::Author->has_many(
285 'My::DBIC::Schema::Book',
289 My::DBIC::Schema::Author->has_many(
291 'My::DBIC::Schema::Book',
292 { 'foreign.author_id' => 'self.id' },
297 # resultset of Books belonging to author
298 my $booklist = $author->books;
300 # resultset of Books belonging to author, restricted by author name
301 my $booklist = $author->books({
302 name => { LIKE => '%macaroni%' },
303 { prefetch => [qw/book/],
306 # array of Book objects belonging to author
307 my @book_objs = $author->books;
309 # force resultset even in list context
310 my $books_rs = $author->books;
311 ( $books_rs ) = $obj->books_rs;
313 # create a new book for this author, the relation fields are auto-filled
314 $author->create_related('books', \%col_data);
315 # alternative method for the above
316 $author->add_to_books(\%col_data);
319 Three methods are created when you create a has_many relationship. The first
320 method is the expected accessor method, C<$accessor_name()>. The second is
321 almost exactly the same as the accessor method but "_rs" is added to the end of
322 the method name. This method works just like the normal accessor, except that
323 it always returns a resultset, even in list context. The third method,
324 named C<< add_to_$relname >>, will also be added to your Row items; this
325 allows you to insert new related items, using the same mechanism as in
326 L<DBIx::Class::Relationship::Base/"create_related">.
328 If you delete an object in a class with a C<has_many> relationship, all
329 the related objects will be deleted as well. To turn this behaviour off,
330 pass C<< cascade_delete => 0 >> in the C<attr> hashref. However, any
331 database-level cascade or restrict will take precedence over a
332 DBIx-Class-based cascading delete.
334 If you copy an object in a class with a C<has_many> relationship, all
335 the related objects will be copied as well. To turn this behaviour off,
336 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
337 defaults to C<< cascade_copy => 1 >>.
339 See L<DBIx::Class::Relationship::Base> for documentation on relationship
340 methods and valid relationship attributes.
346 =item Arguments: $accessor_name, $related_class, $foreign_key_column|\%cond|\@cond?, \%attr?
350 Creates an optional one-to-one relationship with a class. This relationship
351 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
352 resolve the join, unless C<$foreign_key_column> specifies the foreign key
353 column in C<$related_class> or C<cond> specifies a reference to a join
360 This argument is the name of the method you can call on a
361 L<DBIx::Class::Row> object to retrieve the instance of the foreign
362 class matching this relationship. This is often called the
363 C<relation(ship) name>.
365 Use this accessor_name in L<DBIx::Class::ResultSet/join>
366 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
367 indicated by this relationship.
371 This is the class name of the table which contains a foreign key
372 column containing PK values of this class.
374 =item foreign_key_column
376 The column name on the related class that contains the foreign key.
382 A hashref where the keys are C<foreign.$column_on_related_table> and
383 the values are C<self.$foreign_key_column>. This is useful for
384 relations that are across multiple columns.
388 # Author may have an entry in the pseudonym table
389 My::DBIC::Schema::Author->might_have(
391 'My::DBIC::Schema::Pseudonym',
395 # OR (same result, assuming the related_class stores our PK)
396 My::DBIC::Schema::Author->might_have(
398 'My::DBIC::Schema::Pseudonym',
402 My::DBIC::Schema::Author->might_have(
404 'My::DBIC::Schema::Pseudonym',
405 { 'foreign.author_id' => 'self.id' },
409 my $pname = $author->pseudonym; # to get the Pseudonym object
411 If you update or delete an object in a class with a C<might_have>
412 relationship, the related object will be updated or deleted as well. To
413 turn off this behavior, add C<< cascade_delete => 0 >> to the C<$attr>
414 hashref. Any database-level update or delete constraints will override
417 See L<DBIx::Class::Relationship::Base> for documentation on relationship
418 methods and valid relationship attributes.
424 =item Arguments: $accessor_name, $related_class, $foreign_key_column|\%cond|\@cond?, \%attr?
428 Creates a one-to-one relationship with a class. This relationship
429 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
430 resolve the join, unless C<$foreign_key_column> specifies the foreign key
431 column in C<$related_class> or C<cond> specifies a reference to a join
438 This argument is the name of the method you can call on a
439 L<DBIx::Class::Row> object to retrieve the instance of the foreign
440 class matching this relationship. This is often called the
441 C<relation(ship) name>.
443 Use this accessor_name in L<DBIx::Class::ResultSet/join>
444 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
445 indicated by this relationship.
449 This is the class name of the table which contains a foreign key
450 column containing PK values of this class.
452 =item foreign_key_column
454 The column name on the related class that contains the foreign key.
460 A hashref where the keys are C<foreign.$column_on_related_table> and
461 the values are C<self.$foreign_key_column>. This is useful for
462 relations that are across multiple columns.
466 # Every book has exactly one ISBN
467 My::DBIC::Schema::Book->has_one(
469 'My::DBIC::Schema::ISBN',
473 # OR (same result, assuming related_class stores our PK)
474 My::DBIC::Schema::Book->has_one(
476 'My::DBIC::Schema::ISBN',
480 My::DBIC::Schema::Book->has_one(
482 'My::DBIC::Schema::ISBN',
483 { 'foreign.book_id' => 'self.id' },
487 my $isbn_obj = $book->isbn; # to get the ISBN object
489 Creates a one-to-one relationship with another class. This is just
490 like C<might_have>, except the implication is that the other object is
491 always present. The only difference between C<has_one> and
492 C<might_have> is that C<has_one> uses an (ordinary) inner join,
493 whereas C<might_have> defaults to a left join.
495 The has_one relationship should be used when a row in the table has exactly one
496 related row in another table. If the related row might not exist in the foreign
497 table, use the L<DBIx::Class::Relationship/might_have> relationship.
499 In the above example, each Book in the database is associated with exactly one
502 See L<DBIx::Class::Relationship::Base> for documentation on relationship
503 methods and valid relationship attributes.
509 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, \%attr?
513 C<many_to_many> is not strictly a relationship in its own right. Instead, it is
514 a bridge between two resultsets which provide the same kind of convenience
515 accessors as true relationships provide. Although the accessor will return a
516 resultset or collection of objects just like has_many does, you cannot call
517 C<related_resultset> and similar methods which operate on true relationships.
523 This argument is the name of the method you can call on a
524 L<DBIx::Class::Row> object to retrieve the rows matching this
527 On a many_to_many, unlike other relationships, this cannot be used in
528 L<DBIx::Class::ResultSet/search> to join tables. Use the relations
529 bridged across instead.
533 This is the accessor_name from the has_many relationship we are
536 =item foreign_rel_name
538 This is the accessor_name of the belongs_to relationship in the link
539 table that we are bridging across (which gives us the table we are
544 To create a many_to_many relationship from Actor to Role:
546 My::DBIC::Schema::Actor->has_many( actor_roles =>
547 'My::DBIC::Schema::ActorRoles',
549 My::DBIC::Schema::ActorRoles->belongs_to( role =>
550 'My::DBIC::Schema::Role' );
551 My::DBIC::Schema::ActorRoles->belongs_to( actor =>
552 'My::DBIC::Schema::Actor' );
554 My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
557 And, for the reverse relationship, from Role to Actor:
559 My::DBIC::Schema::Role->has_many( actor_roles =>
560 'My::DBIC::Schema::ActorRoles',
563 My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
565 To add a role for your actor, and fill in the year of the role in the
568 $actor->add_to_roles($role, { year => 1995 });
570 In the above example, ActorRoles is the link table class, and Role is the
571 foreign class. The C<$link_rel_name> parameter is the name of the accessor for
572 the has_many relationship from this table to the link table, and the
573 C<$foreign_rel_name> parameter is the accessor for the belongs_to relationship
574 from the link table to the foreign table.
576 To use many_to_many, existing relationships from the original table to the link
577 table, and from the link table to the end table must already exist, these
578 relation names are then used in the many_to_many call.
580 In the above example, the Actor class will have 3 many_to_many accessor methods
581 set: C<roles>, C<add_to_roles>, C<set_roles>, and similarly named accessors
582 will be created for the Role class for the C<actors> many_to_many
585 See L<DBIx::Class::Relationship::Base> for documentation on relationship
586 methods and valid relationship attributes.
598 You may distribute this code under the same terms as Perl itself.