1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 use Scalar::Util qw/weaken blessed/;
14 DBIx::Class::Relationship::Base - Inter-table relationships
18 __PACKAGE__->add_relationship(
19 spiders => 'My::DB::Result::Creatures',
23 "$args->{foreign_alias}.id" => { -ident => "$args->{self_alias}.id" },
24 "$args->{foreign_alias}.type" => 'arachnid'
31 This class provides methods to describe the relationships between the
32 tables in your database model. These are the "bare bones" relationships
33 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
37 =head2 add_relationship
41 =item Arguments: 'relname', 'Foreign::Class', $condition, $attrs
45 __PACKAGE__->add_relationship('relname',
49 Create a custom relationship between one result source and another
50 source, indicated by its class name.
54 The condition argument describes the C<ON> clause of the C<JOIN>
55 expression used to connect the two sources when creating SQL queries.
57 To create simple equality joins, supply a hashref containing the
58 remote table column name as the key(s), and the local table column
59 name as the value(s), for example given:
61 My::Schema::Author->has_many(
62 books => 'My::Schema::Book',
63 { 'foreign.author_id' => 'self.id' }
68 $author_rs->search_related('books')->next
70 will result in the following C<JOIN> clause:
72 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
74 This describes a relationship between the C<Author> table and the
75 C<Book> table where the C<Book> table has a column C<author_id>
76 containing the ID value of the C<Author>.
78 C<foreign> and C<self> are pseudo aliases and must be entered
79 literally. They will be replaced with the actual correct table alias
80 when the SQL is produced.
84 My::Schema::Book->has_many(
85 editions => 'My::Schema::Edition',
87 'foreign.publisher_id' => 'self.publisher_id',
88 'foreign.type_id' => 'self.type_id',
94 $book_rs->search_related('editions')->next
96 will result in the C<JOIN> clause:
99 LEFT JOIN edition editions ON
100 editions.publisher_id = me.publisher_id
101 AND editions.type_id = me.type_id ...
103 This describes the relationship from C<Book> to C<Edition>, where the
104 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
106 As is the default in L<SQL::Abstract>, the key-value pairs will be
107 C<AND>ed in the result. C<OR> can be achieved with an arrayref, for
108 example a condition like:
110 My::Schema::Item->has_many(
111 related_item_links => My::Schema::Item::Links,
113 { 'foreign.left_itemid' => 'self.id' },
114 { 'foreign.right_itemid' => 'self.id' },
118 will translate to the following C<JOIN> clause:
120 ... FROM item me JOIN item_relations related_item_links ON
121 related_item_links.left_itemid = me.id
122 OR related_item_links.right_itemid = me.id ...
124 This describes the relationship from C<Item> to C<Item::Links>, where
125 C<Item::Links> is a many-to-many linking table, linking items back to
126 themselves in a peer fashion (without a "parent-child" designation)
128 To specify joins which describe more than a simple equality of column
129 values, the custom join condition coderef syntax can be used. For
132 My::Schema::Artist->has_many(
133 cds_80s => 'My::Schema::CD',
138 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
139 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
146 $artist_rs->search_related('cds_80s')->next;
148 will result in the C<JOIN> clause:
150 ... FROM artist me LEFT JOIN cd cds_80s ON
151 cds_80s.artist = me.artistid
155 with the bind values:
159 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
160 same values that would be otherwise substituted for C<foreign> and C<self>
161 in the simple hashref syntax case.
163 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
164 like what one would supply as the first argument to
165 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
166 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
167 clause of the C<JOIN> statement associated with this relationship.
169 While every coderef-based condition must return a valid C<ON> clause, it may
170 elect to additionally return a simplified join-free condition hashref when
171 invoked as C<< $row_object->relationship >>, as opposed to
172 C<< $rs->related_resultset('relationship') >>. In this case C<$row_object> is
173 passed to the coderef as C<< $args->{self_rowobj} >>, so a user can do the
181 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
182 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
184 $args->{self_rowobj} && {
185 "$args->{foreign_alias}.artist" => $args->{self_rowobj}->artistid,
186 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
193 my $artist = $schema->resultset("Artist")->find({ id => 4 });
194 $artist->cds_80s->all;
196 Can skip a C<JOIN> altogether and instead produce:
198 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
200 WHERE cds_80s.artist = ?
204 With the bind values:
208 Note that in order to be able to use
209 L<< $row->create_related|DBIx::Class::Relationship::Base/create_related >>,
210 the coderef must not only return as its second such a "simple" condition
211 hashref which does not depend on joins being available, but the hashref must
212 contain only plain values/deflatable objects, such that the result can be
213 passed directly to L<DBIx::Class::Relationship::Base/set_from_related>. For
214 instance the C<year> constraint in the above example prevents the relationship
215 from being used to to create related objects (an exception will be thrown).
217 In order to allow the user to go truly crazy when generating a custom C<ON>
218 clause, the C<$args> hashref passed to the subroutine contains some extra
219 metadata. Currently the supplied coderef is executed as:
221 $relationship_info->{cond}->({
222 self_alias => The alias of the invoking resultset ('me' in case of a row object),
223 foreign_alias => The alias of the to-be-joined resultset (often matches relname),
224 self_resultsource => The invocant's resultsource,
225 foreign_relname => The relationship name (does *not* always match foreign_alias),
226 self_rowobj => The invocant itself in case of $row_obj->relationship
231 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
232 be used as relationship attributes. In particular, the 'where' attribute is
233 useful for filtering relationships:
235 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
236 { 'foreign.user_id' => 'self.user_id' },
237 { where => { valid => 1 } }
240 The following attributes are also valid:
246 Explicitly specifies the type of join to use in the relationship. Any SQL
247 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
248 command immediately before C<JOIN>.
250 =item proxy =E<gt> $column | \@columns | \%column
256 An arrayref containing a list of accessors in the foreign class to create in
257 the main class. If, for example, you do the following:
259 MyDB::Schema::CD->might_have(liner_notes => 'MyDB::Schema::LinerNotes',
261 proxy => [ qw/notes/ ],
264 Then, assuming MyDB::Schema::LinerNotes has an accessor named notes, you can do:
266 my $cd = MyDB::Schema::CD->find(1);
267 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
268 # created if it doesn't exist
272 A hashref where each key is the accessor you want installed in the main class,
273 and its value is the name of the original in the fireign class.
275 MyDB::Schema::Track->belongs_to( cd => 'DBICTest::Schema::CD', 'cd', {
276 proxy => { cd_title => 'title' },
279 This will create an accessor named C<cd_title> on the C<$track> row object.
283 NOTE: you can pass a nested struct too, for example:
285 MyDB::Schema::Track->belongs_to( cd => 'DBICTest::Schema::CD', 'cd', {
286 proxy => [ 'year', { cd_title => 'title' } ],
291 Specifies the type of accessor that should be created for the relationship.
292 Valid values are C<single> (for when there is only a single related object),
293 C<multi> (when there can be many), and C<filter> (for when there is a single
294 related object, but you also want the relationship accessor to double as
295 a column accessor). For C<multi> accessors, an add_to_* method is also
296 created, which calls C<create_related> for the relationship.
298 =item is_foreign_key_constraint
300 If you are using L<SQL::Translator> to create SQL for you and you find that it
301 is creating constraints where it shouldn't, or not creating them where it
302 should, set this attribute to a true or false value to override the detection
303 of when to create constraints.
307 If C<cascade_copy> is true on a C<has_many> relationship for an
308 object, then when you copy the object all the related objects will
309 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
310 in the C<$attr> hashref.
312 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
317 By default, DBIx::Class cascades deletes across C<has_many>,
318 C<has_one> and C<might_have> relationships. You can disable this
319 behaviour on a per-relationship basis by supplying
320 C<< cascade_delete => 0 >> in the relationship attributes.
322 The cascaded operations are performed after the requested delete,
323 so if your database has a constraint on the relationship, it will
324 have deleted/updated the related records or raised an exception
325 before DBIx::Class gets to perform the cascaded operation.
329 By default, DBIx::Class cascades updates across C<has_one> and
330 C<might_have> relationships. You can disable this behaviour on a
331 per-relationship basis by supplying C<< cascade_update => 0 >> in
332 the relationship attributes.
334 This is not a RDMS style cascade update - it purely means that when
335 an object has update called on it, all the related objects also
336 have update called. It will not change foreign keys automatically -
337 you must arrange to do this yourself.
339 =item on_delete / on_update
341 If you are using L<SQL::Translator> to create SQL for you, you can use these
342 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
343 type. If not supplied the SQLT parser will attempt to infer the constraint type by
344 interrogating the attributes of the B<opposite> relationship. For any 'multi'
345 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
346 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
347 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
348 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
349 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
350 C<< on_delete => '' >>, and the same for C<on_update> respectively.
354 Tells L<SQL::Translator> that the foreign key constraint it creates should be
355 deferrable. In other words, the user may request that the constraint be ignored
356 until the end of the transaction. Currently, only the PostgreSQL producer
357 actually supports this.
361 Tells L<SQL::Translator> to add an index for this constraint. Can also be
362 specified globally in the args to L<DBIx::Class::Schema/deploy> or
363 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
367 =head2 register_relationship
371 =item Arguments: $relname, $rel_info
375 Registers a relationship on the class. This is called internally by
376 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
380 sub register_relationship { }
382 =head2 related_resultset
386 =item Arguments: $relationship_name
388 =item Return Value: $related_resultset
392 $rs = $cd->related_resultset('artist');
394 Returns a L<DBIx::Class::ResultSet> for the relationship named
399 sub related_resultset {
401 $self->throw_exception("Can't call *_related as class methods")
404 my $rel_info = $self->relationship_info($rel);
405 $self->throw_exception( "No such relationship ${rel}" )
408 return $self->{related_resultsets}{$rel} ||= do {
409 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
410 $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
412 $self->throw_exception( "Invalid query: @_" )
413 if (@_ > 1 && (@_ % 2 == 1));
414 my $query = ((@_ > 1) ? {@_} : shift);
416 my $source = $self->result_source;
418 # condition resolution may fail if an incomplete master-object prefetch
419 # is encountered - that is ok during prefetch construction (not yet in_storage)
421 # if $rel_info->{cond} is a CODE, we might need to join from the
422 # current resultsource instead of just querying the target
423 # resultsource, in that case, the condition might provide an
424 # additional condition in order to avoid an unecessary join if
425 # that is at all possible.
426 my ($cond, $extended_cond) = try {
427 $source->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel )
430 if ($self->in_storage) {
431 $self->throw_exception ($_);
434 $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION; # RV
437 if ($cond eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
438 my $reverse = $source->reverse_relationship_info($rel);
439 foreach my $rev_rel (keys %$reverse) {
440 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
441 $attrs->{related_objects}{$rev_rel} = [ $self ];
442 weaken $attrs->{related_object}{$rev_rel}[0];
444 $attrs->{related_objects}{$rev_rel} = $self;
445 weaken $attrs->{related_object}{$rev_rel};
450 if (ref $rel_info->{cond} eq 'CODE' && !$extended_cond) {
451 # since we don't have the extended condition, we need to step
452 # back, get a resultset for the current row and do a
453 # search_related there.
455 my $row_srcname = $source->source_name;
456 my $base_rs_class = $source->resultset_class;
457 my $base_rs_attr = $source->resultset_attributes;
458 my $base_rs = $base_rs_class->new
462 alias => $source->storage->relname_to_table_alias(lc($row_srcname).'__row',1)
464 my $alias = $base_rs->current_source_alias;
465 my %identity = map { ( "${alias}.${_}" => $self->get_column($_) ) } $source->primary_columns;
466 my $row_rs = $base_rs->search(\%identity);
467 my $related = $row_rs->related_resultset($rel, { %$attrs, alias => 'me' });
468 $related->search($query);
471 # when we have the extended condition or we have a simple
472 # relationship declaration, it can optimize the JOIN away by
473 # simply adding the identity in WHERE.
475 if (ref $rel_info->{cond} eq 'CODE' && $extended_cond) {
476 $cond = $extended_cond;
479 if (ref $cond eq 'ARRAY') {
481 if (ref $_ eq 'HASH') {
483 foreach my $key (keys %$_) {
484 my $newkey = $key !~ /\./ ? "me.$key" : $key;
485 $hash->{$newkey} = $_->{$key};
492 } elsif (ref $cond eq 'HASH') {
493 foreach my $key (grep { ! /\./ } keys %$cond) {
494 $cond->{"me.$key"} = delete $cond->{$key};
498 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
499 $self->result_source->related_source($rel)->resultset->search(
505 =head2 search_related
507 @objects = $rs->search_related('relname', $cond, $attrs);
508 $objects_rs = $rs->search_related('relname', $cond, $attrs);
510 Run a search on a related resultset. The search will be restricted to the
511 item or items represented by the L<DBIx::Class::ResultSet> it was called
512 upon. This method can be called on a ResultSet, a Row or a ResultSource class.
517 return shift->related_resultset(shift)->search(@_);
520 =head2 search_related_rs
522 ( $objects_rs ) = $rs->search_related_rs('relname', $cond, $attrs);
524 This method works exactly the same as search_related, except that
525 it guarantees a resultset, even in list context.
529 sub search_related_rs {
530 return shift->related_resultset(shift)->search_rs(@_);
535 $obj->count_related('relname', $cond, $attrs);
537 Returns the count of all the items in the related resultset, restricted by the
538 current item or where conditions. Can be called on a
539 L<DBIx::Class::Manual::Glossary/"ResultSet"> or a
540 L<DBIx::Class::Manual::Glossary/"Row"> object.
546 return $self->search_related(@_)->count;
551 my $new_obj = $obj->new_related('relname', \%col_data);
553 Create a new item of the related foreign class. If called on a
554 L<Row|DBIx::Class::Manual::Glossary/"Row"> object, it will magically
555 set any foreign key columns of the new object to the related primary
556 key columns of the source object for you. The newly created item will
557 not be saved into your storage until you call L<DBIx::Class::Row/insert>
563 my ($self, $rel, $values, $attrs) = @_;
564 return $self->search_related($rel)->new($values, $attrs);
567 =head2 create_related
569 my $new_obj = $obj->create_related('relname', \%col_data);
571 Creates a new item, similarly to new_related, and also inserts the item's data
572 into your storage medium. See the distinction between C<create> and C<new>
573 in L<DBIx::Class::ResultSet> for details.
581 $self->throw_exception("Can't call *_related as class methods")
584 # we need to stop and check if this is at all possible. If this is
585 # an extended relationship with an incomplete definition, we should
586 # just forbid it right now.
587 my $rel_info = $self->result_source->relationship_info($rel);
588 if (ref $rel_info->{cond} eq 'CODE') {
589 my ($cond, $ext) = $rel_info->{cond}->({
591 foreign_alias => $rel,
592 self_rowobj => $self,
593 self_resultsource => $self->result_source,
594 foreign_relname => $rel,
596 $self->throw_exception("unable to set_from_related - no simplified condition available for '${rel}'")
599 # now we need to make sure all non-identity relationship
600 # definitions are overriden.
602 while ( my($col, $value) = each %$ext ) {
604 my $vref = ref $value;
605 if ($vref eq 'HASH') {
606 if (keys(%$value) && (keys %$value)[0] ne '=' &&
607 !exists $argref->{$col}) {
608 $self->throw_exception("unable to set_from_related via complex '${rel}' condition on column(s): '${col}'")
614 my $obj = $self->search_related($rel)->create(@_);
615 delete $self->{related_resultsets}->{$rel};
621 my $found_item = $obj->find_related('relname', @pri_vals | \%pri_vals);
623 Attempt to find a related object using its primary key or unique constraints.
624 See L<DBIx::Class::ResultSet/find> for details.
631 return $self->search_related($rel)->find(@_);
634 =head2 find_or_new_related
636 my $new_obj = $obj->find_or_new_related('relname', \%col_data);
638 Find an item of a related class. If none exists, instantiate a new item of the
639 related class. The object will not be saved into your storage until you call
640 L<DBIx::Class::Row/insert> on it.
644 sub find_or_new_related {
646 my $obj = $self->find_related(@_);
647 return defined $obj ? $obj : $self->new_related(@_);
650 =head2 find_or_create_related
652 my $new_obj = $obj->find_or_create_related('relname', \%col_data);
654 Find or create an item of a related class. See
655 L<DBIx::Class::ResultSet/find_or_create> for details.
659 sub find_or_create_related {
661 my $obj = $self->find_related(@_);
662 return (defined($obj) ? $obj : $self->create_related(@_));
665 =head2 update_or_create_related
667 my $updated_item = $obj->update_or_create_related('relname', \%col_data, \%attrs?);
669 Update or create an item of a related class. See
670 L<DBIx::Class::ResultSet/update_or_create> for details.
674 sub update_or_create_related {
677 return $self->related_resultset($rel)->update_or_create(@_);
680 =head2 set_from_related
682 $book->set_from_related('author', $author_obj);
683 $book->author($author_obj); ## same thing
685 Set column values on the current object, using related values from the given
686 related object. This is used to associate previously separate objects, for
687 example, to set the correct author for a book, find the Author object, then
688 call set_from_related on the book.
690 This is called internally when you pass existing objects as values to
691 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
693 The columns are only set in the local copy of the object, call L</update> to
694 set them in the storage.
698 sub set_from_related {
699 my ($self, $rel, $f_obj) = @_;
700 my $rel_info = $self->relationship_info($rel);
701 $self->throw_exception( "No such relationship ${rel}" ) unless $rel_info;
702 my $cond = $rel_info->{cond};
703 $self->throw_exception(
704 "set_from_related can only handle a hash condition; the ".
705 "condition for $rel is of type ".
706 (ref $cond ? ref $cond : 'plain scalar')
707 ) unless ref $cond eq 'HASH';
708 if (defined $f_obj) {
709 my $f_class = $rel_info->{class};
710 $self->throw_exception( "Object $f_obj isn't a ".$f_class )
711 unless blessed $f_obj and $f_obj->isa($f_class);
714 # _resolve_condition might return two hashrefs, specially in the
715 # current case, since we know $f_object is an object.
716 my ($condref1, $condref2) = $self->result_source->_resolve_condition
717 ($rel_info->{cond}, $f_obj, $rel, $rel);
719 # if we get two condrefs, we need to use the second, otherwise we
721 $self->set_columns($condref2 ? $condref2 : $condref1);
726 =head2 update_from_related
728 $book->update_from_related('author', $author_obj);
730 The same as L</"set_from_related">, but the changes are immediately updated
735 sub update_from_related {
737 $self->set_from_related(@_);
741 =head2 delete_related
743 $obj->delete_related('relname', $cond, $attrs);
745 Delete any related item subject to the given conditions.
751 my $obj = $self->search_related(@_)->delete;
752 delete $self->{related_resultsets}->{$_[0]};
758 B<Currently only available for C<has_many>, C<many-to-many> and 'multi' type
763 =item Arguments: ($foreign_vals | $obj), $link_vals?
767 my $role = $schema->resultset('Role')->find(1);
768 $actor->add_to_roles($role);
769 # creates a My::DBIC::Schema::ActorRoles linking table row object
771 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
772 # creates a new My::DBIC::Schema::Role row object and the linking table
773 # object with an extra column in the link
775 Adds a linking table object for C<$obj> or C<$foreign_vals>. If the first
776 argument is a hash reference, the related object is created first with the
777 column values in the hash. If an object reference is given, just the linking
778 table object is created. In either case, any additional column values for the
779 linking table object can be specified in C<$link_vals>.
783 B<Currently only available for C<many-to-many> relationships.>
787 =item Arguments: (\@hashrefs | \@objs), $link_vals?
791 my $actor = $schema->resultset('Actor')->find(1);
792 my @roles = $schema->resultset('Role')->search({ role =>
793 { '-in' => ['Fred', 'Barney'] } } );
795 $actor->set_roles(\@roles);
796 # Replaces all of $actor's previous roles with the two named
798 $actor->set_roles(\@roles, { salary => 15_000_000 });
799 # Sets a column in the link table for all roles
802 Replace all the related objects with the given reference to a list of
803 objects. This does a C<delete> B<on the link table resultset> to remove the
804 association between the current object and all related objects, then calls
805 C<add_to_$rel> repeatedly to link all the new objects.
807 Note that this means that this method will B<not> delete any objects in the
808 table on the right side of the relation, merely that it will delete the link
811 Due to a mistake in the original implementation of this method, it will also
812 accept a list of objects or hash references. This is B<deprecated> and will be
813 removed in a future version.
815 =head2 remove_from_$rel
817 B<Currently only available for C<many-to-many> relationships.>
821 =item Arguments: $obj
825 my $role = $schema->resultset('Role')->find(1);
826 $actor->remove_from_roles($role);
827 # removes $role's My::DBIC::Schema::ActorRoles linking table row object
829 Removes the link between the current object and the related object. Note that
830 the related object itself won't be deleted unless you call ->delete() on
831 it. This method just removes the link between the two objects.
835 Matt S. Trout <mst@shadowcatsystems.co.uk>
839 You may distribute this code under the same terms as Perl itself.