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 MyDB::Schema::Actor->has_many('actorroles' => 'MyDB::Schema::ActorRole',
24 MyDB::Schema::Role->has_many('actorroles' => 'MyDB::Schema::ActorRole',
26 MyDB::Schema::ActorRole->belongs_to('role' => 'MyDB::Schema::Role');
27 MyDB::Schema::ActorRole->belongs_to('actor' => 'MyDB::Schema::Actor');
29 MyDB::Schema::Role->many_to_many('actors' => 'actorroles', 'actor');
30 MyDB::Schema::Actor->many_to_many('roles' => 'actorroles', 'role');
32 $schema->resultset('Actor')->roles();
33 $schema->resultset('Role')->search_related('actors', { Name => 'Fred' });
34 $schema->resultset('ActorRole')->add_to_roles({ Name => 'Sherlock Holmes'});
36 See L<DBIx::Class::Manual::Cookbook> for more.
40 This class provides methods to set up relationships between the tables
41 in your database model. Relationships are the most useful and powerful
42 technique that L<DBIx::Class> provides. To create efficient database queries,
43 create relationships between any and all tables that have something in
44 common, for example if you have a table Authors:
55 1 | 1 | Rulers of the universe
56 2 | 1 | Rulers of the galaxy
58 Then without relationships, the method of getting all books by Fred goes like
61 my $fred = $schema->resultset('Author')->find({ Name => 'Fred' });
62 my $fredsbooks = $schema->resultset('Book')->search({ Author => $fred->ID });
64 With a has_many relationship called "books" on Author (see below for details),
65 we can do this instead:
67 my $fredsbooks = $schema->resultset('Author')->find({ Name => 'Fred' })->books;
69 Each relationship sets up an accessor method on the
70 L<DBIx::Class::Manual::Glossary/"Row"> objects that represent the items
71 of your table. From L<DBIx::Class::Manual::Glossary/"ResultSet"> objects,
72 the relationships can be searched using the "search_related" method.
73 In list context, each returns a list of Row objects for the related class,
74 in scalar context, a new ResultSet representing the joined tables is
75 returned. Thus, the calls can be chained to produce complex queries.
76 Since the database is not actually queried until you attempt to retrieve
77 the data for an actual item, no time is wasted producing them.
79 my $cheapfredbooks = $schema->resultset('Author')->find({
81 })->books->search_related('prices', {
82 Price => { '<=' => '5.00' },
85 will produce a query something like:
87 SELECT * FROM Author me
88 LEFT JOIN Books books ON books.author = me.id
89 LEFT JOIN Prices prices ON prices.book = books.id
90 WHERE prices.Price <= 5.00
92 all without needing multiple fetches.
94 Only the helper methods for setting up standard relationship types
95 are documented here. For the basic, lower-level methods, and a description
96 of all the useful *_related methods that you get for free, see
97 L<DBIx::Class::Relationship::Base>.
101 All helper methods are called similar to the following template:
103 __PACKAGE__->$method_name('relname', 'Foreign::Class', $cond, $attrs);
105 Both C<$cond> and C<$attrs> are optional. Pass C<undef> for C<$cond> if
106 you want to use the default value for it, but still want to set C<$attrs>.
108 See L<DBIx::Class::Relationship::Base> for documentation on the
109 attrubutes that are allowed in the C<$attrs> argument.
116 =item Arguments: $accessor_name, $related_class, $fk_column|$cond?, $attr?
120 Creates a relationship where the calling class stores the foreign class's
121 primary key in one (or more) of its columns. This relationship defaults to
122 using C<$accessor_name> as the foreign key in C<$related_class> to resolve the
123 join, unless C<$fk_column> specifies the foreign key column in
124 this class or C<$cond> specifies a reference to a join condition hash.
130 This argument is the name of the method you can call on a
131 L<DBIx::Class::Row> object to retrieve the instance of the foreign
132 class matching this relationship. This is often called the
133 C<relation(ship) name>.
135 Use this accessor_name in L<DBIx::Class::ResultSet/join>
136 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
137 indicated by this relationship.
141 This is the class name of the table referenced by the foreign key in
146 The column name on this class that contains the foreign key.
152 A hashref where the keys are C<foreign.$column_on_related_table> and
153 the values are C<self.$foreign_key_column>. This is useful for
154 relations that are across multiple columns.
159 # in a Book class (where Author has many Books)
160 My::DBIC::Schema::Book->belongs_to( author => 'My::DBIC::Schema::Author' );
162 my $author_obj = $obj->author; # get author object
163 $obj->author( $new_author_obj ); # set author object
165 The above belongs_to relationship could also have been specified as,
167 My::DBIC::Schema::Book->belongs_to( author,
168 'My::DBIC::Schema::Author',
169 { 'foreign.author' => 'self.author' } );
171 If the relationship is optional -- i.e. the column containing the foreign key
172 can be NULL -- then the belongs_to relationship does the right thing. Thus, in
173 the example above C<$obj-E<gt>author> would return C<undef>. However in this
174 case you would probably want to set the C<join_type> attribute so that a C<LEFT
175 JOIN> is done, which makes complex resultsets involving C<join> or C<prefetch>
176 operations work correctly. The modified declaration is shown below:
178 # in a Book class (where Author has_many Books)
179 __PACKAGE__->belongs_to(author => 'My::DBIC::Schema::Author',
180 'author', {join_type => 'left'});
183 Cascading deletes are off by default on a C<belongs_to>
184 relationship. To turn them on, pass C<< cascade_delete => 1 >>
185 in the $attr hashref.
187 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
190 See L<DBIx::Class::Relationship::Base> for documentation on relationship
191 methods and valid relationship attributes.
197 =item Arguments: $accessor_name, $related_class, $foreign_key_column|$cond?, $attr?
201 Creates a one-to-many relationship, where the corresponding elements of the
202 foreign class store the calling class's primary key in one (or more) of its
203 columns. This relationship defaults to using C<$accessor_name> as the foreign
204 key in C<$related_class> to resolve the join, unless C<$foreign_key_column>
205 specifies the foreign key column in C<$related_class> or C<$cond> specifies a
206 reference to a join condition hash.
212 This argument is the name of the method you can call on a
213 L<DBIx::Class::Row> object to retrieve a resultset of the related
214 class restricted to the ones related to the row object. In list
215 context it returns the row objects.
217 Use this accessor_name (relation name) in L<DBIx::Class::ResultSet/join>
218 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
219 indicated by this relationship.
223 This is the class name of the table which contains a foreign key
224 column containing PK values of this class.
226 =item foreign_key_column
228 The column name on the related class that contains the foreign key.
234 A hashref where the keys are C<foreign.$column_on_related_table> and
235 the values are C<self.$foreign_key_column>. This is useful for
236 relations that are across multiple columns.
240 # in an Author class (where Author has_many Books)
241 My::DBIC::Schema::Author->has_many(books => 'My::DBIC::Schema::Book', 'author');
243 my $booklist = $obj->books;
244 my $booklist = $obj->books({
245 name => { LIKE => '%macaroni%' },
246 { prefetch => [qw/book/],
248 my @book_objs = $obj->books;
249 my $books_rs = $obj->books;
250 ( $books_rs ) = $obj->books_rs;
252 $obj->add_to_books(\%col_data);
254 The above C<has_many> relationship could also have been specified with an
255 explicit join condition:
257 My::DBIC::Schema::Author->has_many( books => 'My::DBIC::Schema::Book', {
258 'foreign.author' => 'self.author',
261 Three methods are created when you create a has_many relationship. The first
262 method is the expected accessor method, C<$accessor_name()>. The second is
263 almost exactly the same as the accessor method but "_rs" is added to the end of
264 the method name. This method works just like the normal accessor, except that
265 it returns a resultset no matter what, even in list context. The third method,
266 named C<< add_to_$relname >>, will also be added to your Row items; this
267 allows you to insert new related items, using the same mechanism as in
268 L<DBIx::Class::Relationship::Base/"create_related">.
270 If you delete an object in a class with a C<has_many> relationship, all
271 the related objects will be deleted as well. To turn this behaviour off,
272 pass C<< cascade_delete => 0 >> in the C<$attr> hashref. However, any
273 database-level cascade or restrict will take precedence over a
274 DBIx-Class-based cascading delete.
276 If you copy an object in a class with a C<has_many> relationship, all
277 the related objects will be copied as well. To turn this behaviour off,
278 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
279 defaults to C<< cascade_copy => 1 >>.
281 See L<DBIx::Class::Relationship::Base> for documentation on relationship
282 methods and valid relationship attributes.
288 =item Arguments: $accessor_name, $related_class, $foreign_key_column|$cond?, $attr?
292 Creates an optional one-to-one relationship with a class. This relationship
293 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
294 resolve the join, unless C<$foreign_key_column> specifies the foreign key
295 column in C<$related_class> or C<$cond> specifies a reference to a join
302 This argument is the name of the method you can call on a
303 L<DBIx::Class::Row> object to retrieve the instance of the foreign
304 class matching this relationship.
306 Use this accessor_name (relation name) in L<DBIx::Class::ResultSet/join>
307 or L<DBIx::Class::ResultSet/prefetch> to join to the foreign table
308 indicated by this relationship.
312 This is the class name of the table which contains a foreign key
313 column containing PK values of this class.
315 =item foreign_key_column
317 The column name on the related class that contains the foreign key.
323 A hashref where the keys are C<foreign.$column_on_related_table> and
324 the values are C<self.$foreign_key_column>. This is useful for
325 relations that are across multiple columns.
329 My::DBIC::Schema::Author->might_have( pseudonym =>
330 'My::DBIC::Schema::Pseudonym' );
332 my $pname = $obj->pseudonym; # to get the Pseudonym object
334 The above might_have relationship could have been specified as:
336 My::DBIC::Schema::Author->might_have( pseudonym =>
337 'My::DBIC::Schema::Pseudonym',
342 My::DBIC::Schema::Author->might_have( pseudonym =>
343 'My::DBIC::Schema::Pseudonym',
344 { 'foreign.author' => 'self.author' } );
346 If you update or delete an object in a class with a C<might_have>
347 relationship, the related object will be updated or deleted as well. To
348 turn off this behavior, add C<< cascade_delete => 0 >> to the C<$attr>
349 hashref. Any database-level update or delete constraints will override
352 See L<DBIx::Class::Relationship::Base> for documentation on relationship
353 methods and valid relationship attributes.
359 =item Arguments: $accessor_name, $related_class_name, $join_condition?, $attr?
363 My::DBIC::Schema::Book->has_one(isbn => 'My::DBIC::Schema::ISBN');
365 my $isbn_obj = $obj->isbn; # to get the ISBN object
367 Creates a one-to-one relationship with another class. This is just like
368 C<might_have>, except the implication is that the other object is always
369 present. The only difference between C<has_one> and C<might_have> is that
370 C<has_one> uses an (ordinary) inner join, whereas C<might_have> uses a
373 The has_one relationship should be used when a row in the table has exactly one
374 related row in another table. If the related row might not exist in the foreign
375 table, use the L<DBIx::Class::Relationship/might_have> relationship.
377 In the above example, each Book in the database is associated with exactly one
380 See L<DBIx::Class::Relationship::Base> for documentation on relationship
381 methods and valid relationship attributes.
387 =item Arguments: $accessor_name, $link_rel_name, $foreign_rel_name, $attr?
391 C<many_to_many> is not strictly a relationship in its own right. Instead, it is
392 a bridge between two resultsets which provide the same kind of convenience
393 accessors as true relationships provide. Although the accessor will return a
394 resultset or collection of objects just like has_many does, you cannot call
395 C<related_resultset> and similar methods which operate on true relationships.
401 This argument is the name of the method you can call on a
402 L<DBIx::Class::Row> object to retrieve the rows matching this
405 On a many_to_many, unlike other relationships, this cannot be used in
406 L<DBIx::Class::ResultSet/search> to join tables. Use the relations
407 bridged across instead.
411 This is the accessor_name from the has_many relationship we are
414 =item foreign_rel_name
416 This is the accessor_name of the belongs_to relationship in the link
417 table that we are bridging across (which gives us the table we are
422 To create a many_to_many relationship from Actor to Role:
424 My::DBIC::Schema::Actor->has_many( actor_roles =>
425 'My::DBIC::Schema::ActorRoles',
427 My::DBIC::Schema::ActorRoles->belongs_to( role =>
428 'My::DBIC::Schema::Role' );
429 My::DBIC::Schema::ActorRoles->belongs_to( actor =>
430 'My::DBIC::Schema::Actor' );
432 My::DBIC::Schema::Actor->many_to_many( roles => 'actor_roles',
435 And, for the reverse relationship, from Role to Actor:
437 My::DBIC::Schema::Role->has_many( actor_roles =>
438 'My::DBIC::Schema::ActorRoles',
441 My::DBIC::Schema::Role->many_to_many( actors => 'actor_roles', 'actor' );
443 To add a role for your actor, and fill in the year of the role in the
446 $actor->add_to_roles($role, { year => 1995 });
448 In the above example, ActorRoles is the link table class, and Role is the
449 foreign class. The C<$link_rel_name> parameter is the name of the accessor for
450 the has_many relationship from this table to the link table, and the
451 C<$foreign_rel_name> parameter is the accessor for the belongs_to relationship
452 from the link table to the foreign table.
454 To use many_to_many, existing relationships from the original table to the link
455 table, and from the link table to the end table must already exist, these
456 relation names are then used in the many_to_many call.
458 In the above example, the Actor class will have 3 many_to_many accessor methods
459 set: C<$roles>, C<$add_to_roles>, C<$set_roles>, and similarly named accessors
460 will be created for the Role class for the C<actors> many_to_many
463 See L<DBIx::Class::Relationship::Base> for documentation on relationship
464 methods and valid relationship attributes.
472 Matt S. Trout <mst@shadowcatsystems.co.uk>
476 You may distribute this code under the same terms as Perl itself.