1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 use Scalar::Util qw/weaken blessed/;
9 use DBIx::Class::_Util qw(
10 UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
11 dbic_internal_try fail_on_internal_call
13 use DBIx::Class::SQLMaker::Util 'extract_equality_conditions';
14 use DBIx::Class::Carp;
19 DBIx::Class::Relationship::Base - Inter-table relationships
23 __PACKAGE__->add_relationship(
24 spiders => 'My::DB::Result::Creatures',
28 "$args->{foreign_alias}.id" => { -ident => "$args->{self_alias}.id" },
29 "$args->{foreign_alias}.type" => 'arachnid'
36 This class provides methods to describe the relationships between the
37 tables in your database model. These are the "bare bones" relationships
38 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
42 =head2 add_relationship
46 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
50 __PACKAGE__->add_relationship('rel_name',
54 Create a custom relationship between one result source and another
55 source, indicated by its class name.
59 The condition argument describes the C<ON> clause of the C<JOIN>
60 expression used to connect the two sources when creating SQL queries.
62 =head4 Simple equality
64 To create simple equality joins, supply a hashref containing the remote
65 table column name as the key(s) prefixed by C<'foreign.'>, and the
66 corresponding local table column name as the value(s) prefixed by C<'self.'>.
67 Both C<foreign> and C<self> are pseudo aliases and must be entered
68 literally. They will be replaced with the actual correct table alias
69 when the SQL is produced.
73 My::Schema::Author->has_many(
74 books => 'My::Schema::Book',
75 { 'foreign.author_id' => 'self.id' }
80 $author_rs->search_related('books')->next
82 will result in the following C<JOIN> clause:
84 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
86 This describes a relationship between the C<Author> table and the
87 C<Book> table where the C<Book> table has a column C<author_id>
88 containing the ID value of the C<Author>.
92 My::Schema::Book->has_many(
93 editions => 'My::Schema::Edition',
95 'foreign.publisher_id' => 'self.publisher_id',
96 'foreign.type_id' => 'self.type_id',
102 $book_rs->search_related('editions')->next
104 will result in the C<JOIN> clause:
107 LEFT JOIN edition editions ON
108 editions.publisher_id = me.publisher_id
109 AND editions.type_id = me.type_id ...
111 This describes the relationship from C<Book> to C<Edition>, where the
112 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
114 =head4 Multiple groups of simple equality conditions
116 As is the default in L<SQL::Abstract>, the key-value pairs will be
117 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
118 an arrayref. For example a condition like:
120 My::Schema::Item->has_many(
121 related_item_links => My::Schema::Item::Links,
123 { 'foreign.left_itemid' => 'self.id' },
124 { 'foreign.right_itemid' => 'self.id' },
128 will translate to the following C<JOIN> clause:
130 ... FROM item me JOIN item_relations related_item_links ON
131 related_item_links.left_itemid = me.id
132 OR related_item_links.right_itemid = me.id ...
134 This describes the relationship from C<Item> to C<Item::Links>, where
135 C<Item::Links> is a many-to-many linking table, linking items back to
136 themselves in a peer fashion (without a "parent-child" designation)
138 =head4 Custom join conditions
140 NOTE: The custom join condition specification mechanism is capable of
141 generating JOIN clauses of virtually unlimited complexity. This may limit
142 your ability to traverse some of the more involved relationship chains the
143 way you expect, *and* may bring your RDBMS to its knees. Exercise care
144 when declaring relationships as described here.
146 To specify joins which describe more than a simple equality of column
147 values, the custom join condition coderef syntax can be used. For
150 My::Schema::Artist->has_many(
151 cds_80s => 'My::Schema::CD',
156 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
157 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
164 $artist_rs->search_related('cds_80s')->next;
166 will result in the C<JOIN> clause:
168 ... FROM artist me LEFT JOIN cd cds_80s ON
169 cds_80s.artist = me.artistid
173 with the bind values:
177 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
178 same values that would be otherwise substituted for C<foreign> and C<self>
179 in the simple hashref syntax case.
181 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
182 like what one would supply as the first argument to
183 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
184 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
185 clause of the C<JOIN> statement associated with this relationship.
187 While every coderef-based condition must return a valid C<ON> clause, it may
188 elect to additionally return a simplified B<optional> join-free condition
189 consisting of a hashref with B<all keys being fully qualified names of columns
190 declared on the corresponding result source>. This boils down to two scenarios:
196 When relationship resolution is invoked after C<< $result->$rel_name >>, as
197 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
198 is passed to the coderef as C<< $args->{self_result_object} >>.
202 Alternatively when the user-space invokes resolution via
203 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
204 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
205 B<always> in the form of a hashref. If a foreign result object is supplied
206 (which is valid usage of L</set_from_related>), its values will be extracted
207 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
211 Note that the above scenarios are mutually exclusive, that is you will be supplied
212 none or only one of C<self_result_object> and C<foreign_values>. In other words if
213 you define your condition coderef as:
220 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
221 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
223 ! $args->{self_result_object} ? () : {
224 "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
225 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
227 ! $args->{foreign_values} ? () : {
228 "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
235 my $artist = $schema->resultset("Artist")->find({ id => 4 });
236 $artist->cds_80s->all;
238 Can skip a C<JOIN> altogether and instead produce:
240 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
242 WHERE cds_80s.artist = ?
246 With the bind values:
252 my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
253 my $artist = $schema->resultset("Artist")->new({});
254 $artist->set_from_related('cds_80s');
256 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
258 Note that in order to be able to use L</set_from_related> (and by extension
259 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
260 the returned join free condition B<must> contain only plain values/deflatable
261 objects. For instance the C<year> constraint in the above example prevents
262 the relationship from being used to create related objects using
263 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
264 exception will be thrown).
266 In order to allow the user to go truly crazy when generating a custom C<ON>
267 clause, the C<$args> hashref passed to the subroutine contains some extra
268 metadata. Currently the supplied coderef is executed as:
270 $relationship_info->{cond}->({
271 self_resultsource => The resultsource instance on which rel_name is registered
272 rel_name => The relationship name (does *NOT* always match foreign_alias)
274 self_alias => The alias of the invoking resultset
275 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
277 # only one of these (or none at all) will ever be supplied to aid in the
278 # construction of a join-free condition
280 self_result_object => The invocant *object* itself in case of a call like
281 $result_object->$rel_name( ... )
283 foreign_values => A *hashref* of related data: may be passed in directly or
284 derived via ->get_columns() from a related object in case of
285 $result_object->set_from_related( $rel_name, $foreign_result_object )
287 # deprecated inconsistent names, will be forever available for legacy code
288 self_rowobj => Old deprecated slot for self_result_object
289 foreign_relname => Old deprecated slot for rel_name
294 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
295 be used as relationship attributes. In particular, the 'where' attribute is
296 useful for filtering relationships:
298 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
299 { 'foreign.user_id' => 'self.user_id' },
300 { where => { valid => 1 } }
303 The following attributes are also valid:
309 Explicitly specifies the type of join to use in the relationship. Any SQL
310 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
311 command immediately before C<JOIN>.
313 =item proxy =E<gt> $column | \@columns | \%column
315 The 'proxy' attribute can be used to retrieve values, and to perform
316 updates if the relationship has 'cascade_update' set. The 'might_have'
317 and 'has_one' relationships have this set by default; if you want a proxy
318 to update across a 'belongs_to' relationship, you must set the attribute
325 An arrayref containing a list of accessors in the foreign class to create in
326 the main class. If, for example, you do the following:
328 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
330 proxy => [ qw/notes/ ],
333 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
335 my $cd = MyApp::Schema::CD->find(1);
336 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
337 # created if it doesn't exist
339 For a 'belongs_to relationship, note the 'cascade_update':
341 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
342 { proxy => ['title'], cascade_update => 1 }
344 $track->title('New Title');
345 $track->update; # updates title in CD
349 A hashref where each key is the accessor you want installed in the main class,
350 and its value is the name of the original in the foreign class.
352 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
353 proxy => { cd_title => 'title' },
356 This will create an accessor named C<cd_title> on the C<$track> result object.
360 NOTE: you can pass a nested struct too, for example:
362 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
363 proxy => [ 'year', { cd_title => 'title' } ],
368 Specifies the type of accessor that should be created for the relationship.
369 Valid values are C<single> (for when there is only a single related object),
370 C<multi> (when there can be many), and C<filter> (for when there is a single
371 related object, but you also want the relationship accessor to double as
372 a column accessor). For C<multi> accessors, an add_to_* method is also
373 created, which calls C<create_related> for the relationship.
375 =item is_foreign_key_constraint
377 If you are using L<SQL::Translator> to create SQL for you and you find that it
378 is creating constraints where it shouldn't, or not creating them where it
379 should, set this attribute to a true or false value to override the detection
380 of when to create constraints.
384 If C<cascade_copy> is true on a C<has_many> relationship for an
385 object, then when you copy the object all the related objects will
386 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
387 in the C<$attr> hashref.
389 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
394 By default, DBIx::Class cascades deletes across C<has_many>,
395 C<has_one> and C<might_have> relationships. You can disable this
396 behaviour on a per-relationship basis by supplying
397 C<< cascade_delete => 0 >> in the relationship attributes.
399 The cascaded operations are performed after the requested delete,
400 so if your database has a constraint on the relationship, it will
401 have deleted/updated the related records or raised an exception
402 before DBIx::Class gets to perform the cascaded operation.
406 By default, DBIx::Class cascades updates across C<has_one> and
407 C<might_have> relationships. You can disable this behaviour on a
408 per-relationship basis by supplying C<< cascade_update => 0 >> in
409 the relationship attributes.
411 The C<belongs_to> relationship does not update across relationships
412 by default, so if you have a 'proxy' attribute on a belongs_to and want to
413 use 'update' on it, you must set C<< cascade_update => 1 >>.
415 This is not a RDMS style cascade update - it purely means that when
416 an object has update called on it, all the related objects also
417 have update called. It will not change foreign keys automatically -
418 you must arrange to do this yourself.
420 =item on_delete / on_update
422 If you are using L<SQL::Translator> to create SQL for you, you can use these
423 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
424 type. If not supplied the SQLT parser will attempt to infer the constraint type by
425 interrogating the attributes of the B<opposite> relationship. For any 'multi'
426 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
427 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
428 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
429 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
430 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
431 C<< on_delete => '' >>, and the same for C<on_update> respectively.
435 Tells L<SQL::Translator> that the foreign key constraint it creates should be
436 deferrable. In other words, the user may request that the constraint be ignored
437 until the end of the transaction. Currently, only the PostgreSQL producer
438 actually supports this.
442 Tells L<SQL::Translator> to add an index for this constraint. Can also be
443 specified globally in the args to L<DBIx::Class::Schema/deploy> or
444 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
448 =head2 register_relationship
452 =item Arguments: $rel_name, $rel_info
456 Registers a relationship on the class. This is called internally by
457 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
461 sub register_relationship { }
463 =head2 related_resultset
467 =item Arguments: $rel_name
469 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
473 $rs = $cd->related_resultset('artist');
475 Returns a L<DBIx::Class::ResultSet> for the relationship named
478 =head2 $relationship_accessor
482 =item Arguments: none
484 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
488 # These pairs do the same thing
489 $result = $cd->related_resultset('artist')->single; # has_one relationship
490 $result = $cd->artist;
491 $rs = $cd->related_resultset('tracks'); # has_many relationship
494 This is the recommended way to traverse through relationships, based
495 on the L</accessor> name given in the relationship definition.
497 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
498 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
499 C<single> (returns only one row) or C<multi> (returns many rows). The
500 method may also return C<undef> if the relationship doesn't exist for
501 this instance (like in the case of C<might_have> relationships).
505 sub related_resultset {
506 $_[0]->throw_exception(
507 '$result->related_resultset() no longer accepts extra search arguments, '
508 . 'you need to switch to ...->related_resultset($relname)->search_rs(...) '
509 . 'instead (it was never documented and more importantly could never work '
510 . 'reliably due to the heavy caching involved)'
513 $_[0]->throw_exception("Can't call *_related as class methods")
516 return $_[0]->{related_resultsets}{$_[1]}
517 if defined $_[0]->{related_resultsets}{$_[1]};
519 my ($self, $rel) = @_;
521 my $rsrc = $self->result_source;
523 my $rel_info = $rsrc->relationship_info($rel)
524 or $self->throw_exception( "No such relationship '$rel'" );
526 my $relcond_is_freeform = ref $rel_info->{cond} eq 'CODE';
528 my $jfc = $rsrc->_resolve_relationship_condition(
531 self_result_object => $self,
533 # an extra sanity check guard
534 require_join_free_condition => !!(
535 ! $relcond_is_freeform
540 # an API where these are optional would be too cumbersome,
541 # instead always pass in some dummy values
544 # this may look weird, but remember that we are making a resultset
545 # out of an existing object, with the new source being at the head
546 # of the FROM chain. Having a 'me' alias is nothing but expected there
547 foreign_alias => 'me',
549 )->{join_free_condition};
555 $rel_rset = $rsrc->related_source($rel)->resultset->search(
560 elsif( $relcond_is_freeform ) {
562 # A WHOREIFFIC hack to reinvoke the entire condition resolution
563 # with the correct alias. Another way of doing this involves a
564 # lot of state passing around, and the @_ positions are already
565 # mapped out, making this crap a less icky option.
567 # The point of this exercise is to retain the spirit of the original
568 # $obj->search_related($rel) where the resulting rset will have the
569 # root alias as 'me', instead of $rel (as opposed to invoking
570 # $rs->search_related)
572 # make the fake 'me' rel
573 local $rsrc->{_relationships}{me} = {
574 %{ $rsrc->{_relationships}{$rel} },
575 _original_name => $rel,
578 my $obj_table_alias = lc($rsrc->source_name) . '__row';
579 $obj_table_alias =~ s/\W+/_/g;
581 $rel_rset = $rsrc->resultset->search(
582 $self->ident_condition($obj_table_alias),
583 { alias => $obj_table_alias },
584 )->related_resultset('me')->search(undef, $rel_info->{attrs})
588 my $attrs = { %{$rel_info->{attrs}} };
589 my $reverse = $rsrc->reverse_relationship_info($rel);
591 # FIXME - this loop doesn't seem correct - got to figure out
592 # at some point what exactly it does.
593 # See also the FIXME at the end of new_related()
594 ( ( $reverse->{$_}{attrs}{accessor}||'') eq 'multi' )
595 ? weaken( $attrs->{related_objects}{$_}[0] = $self )
596 : weaken( $attrs->{related_objects}{$_} = $self )
599 $rel_rset = $rsrc->related_source($rel)->resultset->search(
600 UNRESOLVABLE_CONDITION, # guards potential use of the $rs in the future
605 $self->{related_resultsets}{$rel} = $rel_rset;
608 =head2 search_related
612 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
614 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
618 Run a search on a related resultset. The search will be restricted to the
619 results represented by the L<DBIx::Class::ResultSet> it was called
622 See L<DBIx::Class::ResultSet/search_related> for more information.
626 sub search_related :DBIC_method_is_indirect_sugar {
627 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
628 shift->related_resultset(shift)->search(@_);
631 =head2 search_related_rs
633 This method works exactly the same as search_related, except that
634 it guarantees a resultset, even in list context.
638 sub search_related_rs :DBIC_method_is_indirect_sugar {
639 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
640 shift->related_resultset(shift)->search_rs(@_)
647 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
649 =item Return Value: $count
653 Returns the count of all the rows in the related resultset, restricted by the
654 current result or where conditions.
658 sub count_related :DBIC_method_is_indirect_sugar {
659 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
660 shift->related_resultset(shift)->search_rs(@_)->count;
667 =item Arguments: $rel_name, \%col_data
669 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
673 Create a new result object of the related foreign class. It will magically set
674 any foreign key columns of the new object to the related primary key columns
675 of the source object for you. The newly created result will not be saved into
676 your storage until you call L<DBIx::Class::Row/insert> on it.
681 my ($self, $rel, $data) = @_;
683 $self->throw_exception(
684 "Result object instantiation requires a hashref as argument"
685 ) unless ref $data eq 'HASH';
687 my $rsrc = $self->result_source;
688 my $rel_rsrc = $rsrc->related_source($rel);
691 ### This section deliberately does not rely on require_join_free_values,
692 ### as quite often the resulting related object is useless without the
693 ### contents of $data mixed in. Originally this code was part of
694 ### resolve_relationship_condition() but given it has a single, very
695 ### context-specific call-site it made no sense to expose it to end users.
698 my $rel_resolution = $rsrc->_resolve_relationship_condition (
700 self_result_object => $self,
702 # In case we are *not* in_storage it is ok to treat failed resolution as an empty hash
703 # This happens e.g. as a result of various in-memory related graph of objects
704 require_join_free_condition => !! $self->in_storage,
706 # dummy aliases with deliberately known lengths, so that we can
707 # quickly strip them below if needed
708 foreign_alias => 'F',
713 $rel_resolution->{join_free_values}
715 { map { substr( $_, 2 ) => $rel_resolution->{join_free_condition}{$_} } keys %{ $rel_resolution->{join_free_condition} } }
718 # mix everything together
719 my $amalgamated_values = {
721 # in case we got back join_free_values - they already have passed the extractor
722 $rel_resolution->{join_free_values}
724 : extract_equality_conditions(
732 # cleanup possible rogue { somecolumn => [ -and => 1,2 ] }
733 ($amalgamated_values->{$_}||'') eq UNRESOLVABLE_CONDITION
735 delete $amalgamated_values->{$_}
736 for keys %$amalgamated_values;
738 if( my @nonvalues = grep { ! exists $amalgamated_values->{$_} } keys %$rel_values ) {
740 $self->throw_exception(
741 "Unable to complete value inferrence - relationship '$rel' "
742 . "on source '@{[ $rsrc->source_name ]}' results "
743 . 'in expression(s) instead of definitive values: '
745 # FIXME - used for diag only, but still icky
747 dbic_internal_try { $rsrc->schema->storage->sql_maker }
750 require DBIx::Class::SQLMaker
752 DBIx::Class::SQLMaker->new
755 local $sqlm->{quote_char};
756 local $sqlm->{_dequalify_idents} = 1;
757 ($sqlm->_recurse_where({ map { $_ => $rel_values->{$_} } @nonvalues }))[0]
762 # And more complications - in case the relationship did not resolve
763 # we *have* to loop things through search_related ( essentially re-resolving
764 # everything we did so far, but with different type of handholding )
765 # FIXME - this is still a mess, just a *little* better than it was
766 # See also the FIXME at the end of related_resultset()
767 exists $rel_resolution->{join_free_values}
768 ? $rel_rsrc->result_class->new({ -result_source => $rel_rsrc, %$amalgamated_values })
769 : $self->related_resultset($rel)->new_result( $amalgamated_values )
773 =head2 create_related
777 =item Arguments: $rel_name, \%col_data
779 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
783 my $result = $obj->create_related($rel_name, \%col_data);
785 Creates a new result object, similarly to new_related, and also inserts the
786 result's data into your storage medium. See the distinction between C<create>
787 and C<new> in L<DBIx::Class::ResultSet> for details.
794 my $obj = $self->new_related($rel, @_)->insert;
795 delete $self->{related_resultsets}->{$rel};
803 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
805 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
809 my $result = $obj->find_related($rel_name, \%col_data);
811 Attempt to find a related object using its primary key or unique constraints.
812 See L<DBIx::Class::ResultSet/find> for details.
816 sub find_related :DBIC_method_is_indirect_sugar {
817 #my ($self, $rel, @args) = @_;
818 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
819 return shift->related_resultset(shift)->find(@_);
822 =head2 find_or_new_related
826 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
828 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
832 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
837 sub find_or_new_related {
840 my $obj = $self->related_resultset($rel)->find(@_);
841 return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
844 =head2 find_or_create_related
848 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
850 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
854 Find or create a result object of a related class. See
855 L<DBIx::Class::ResultSet/find_or_create> for details.
859 sub find_or_create_related {
862 my $obj = $self->related_resultset($rel)->find(@_);
863 return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
866 =head2 update_or_create_related
870 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
872 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
876 Update or create a result object of a related class. See
877 L<DBIx::Class::ResultSet/update_or_create> for details.
881 sub update_or_create_related :DBIC_method_is_indirect_sugar {
882 #my ($self, $rel, @args) = @_;
883 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
884 shift->related_resultset(shift)->update_or_create(@_);
887 =head2 set_from_related
891 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
893 =item Return Value: not defined
897 $book->set_from_related('author', $author_obj);
898 $book->author($author_obj); ## same thing
900 Set column values on the current object, using related values from the given
901 related object. This is used to associate previously separate objects, for
902 example, to set the correct author for a book, find the Author object, then
903 call set_from_related on the book.
905 This is called internally when you pass existing objects as values to
906 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
908 The columns are only set in the local copy of the object, call
909 L<update|DBIx::Class::Row/update> to update them in the storage.
913 sub set_from_related {
914 my ($self, $rel, $f_obj) = @_;
916 $self->set_columns( $self->result_source->_resolve_relationship_condition (
917 require_join_free_values => 1,
920 # maintain crazy set_from_related interface
922 ( ! defined $f_obj ) ? +{}
923 : ( ! defined blessed $f_obj ) ? $f_obj
926 my $f_result_class = $self->result_source->related_source($rel)->result_class;
928 unless( $f_obj->isa($f_result_class) ) {
930 $self->throw_exception(
931 'Object supplied to set_from_related() must inherit from '
932 . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
933 ) unless $f_obj->isa(
934 $DBIx::Class::ResultSource::__expected_result_class_isa
938 'Object supplied to set_from_related() usually should inherit from '
939 . "the related ResultClass ('$f_result_class'), perhaps you've made "
944 +{ $f_obj->get_columns };
948 # an API where these are optional would be too cumbersome,
949 # instead always pass in some dummy values
952 )->{join_free_values} );
957 =head2 update_from_related
961 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
963 =item Return Value: not defined
967 $book->update_from_related('author', $author_obj);
969 The same as L</"set_from_related">, but the changes are immediately updated
974 sub update_from_related {
976 $self->set_from_related(@_);
980 =head2 delete_related
984 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
986 =item Return Value: $underlying_storage_rv
990 Delete any related row, subject to the given conditions. Internally, this
993 $self->search_related(@_)->delete
995 And returns the result of that.
1002 my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
1003 delete $self->{related_resultsets}->{$rel};
1009 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
1012 =head3 has_many / multi
1016 =item Arguments: \%col_data
1018 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1022 Creates/inserts a new result object. Internally, this calls:
1024 $self->create_related($rel, @_)
1026 And returns the result of that.
1032 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
1034 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1038 my $role = $schema->resultset('Role')->find(1);
1039 $actor->add_to_roles($role);
1040 # creates a My::DBIC::Schema::ActorRoles linking table result object
1042 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
1043 # creates a new My::DBIC::Schema::Role result object and the linking table
1044 # object with an extra column in the link
1046 Adds a linking table object. If the first argument is a hash reference, the
1047 related object is created first with the column values in the hash. If an object
1048 reference is given, just the linking table object is created. In either case,
1049 any additional column values for the linking table object can be specified in
1052 See L<DBIx::Class::Relationship/many_to_many> for additional details.
1056 B<Currently only available for C<many_to_many> relationships.>
1060 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
1062 =item Return Value: not defined
1066 my $actor = $schema->resultset('Actor')->find(1);
1067 my @roles = $schema->resultset('Role')->search({ role =>
1068 { '-in' => ['Fred', 'Barney'] } } );
1070 $actor->set_roles(\@roles);
1071 # Replaces all of $actor's previous roles with the two named
1073 $actor->set_roles(\@roles, { salary => 15_000_000 });
1074 # Sets a column in the link table for all roles
1077 Replace all the related objects with the given reference to a list of
1078 objects. This does a C<delete> B<on the link table resultset> to remove the
1079 association between the current object and all related objects, then calls
1080 C<add_to_$rel> repeatedly to link all the new objects.
1082 Note that this means that this method will B<not> delete any objects in the
1083 table on the right side of the relation, merely that it will delete the link
1086 Due to a mistake in the original implementation of this method, it will also
1087 accept a list of objects or hash references. This is B<deprecated> and will be
1088 removed in a future version.
1090 =head2 remove_from_$rel
1092 B<Currently only available for C<many_to_many> relationships.>
1096 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
1098 =item Return Value: not defined
1102 my $role = $schema->resultset('Role')->find(1);
1103 $actor->remove_from_roles($role);
1104 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
1106 Removes the link between the current object and the related object. Note that
1107 the related object itself won't be deleted unless you call ->delete() on
1108 it. This method just removes the link between the two objects.
1110 =head1 FURTHER QUESTIONS?
1112 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1114 =head1 COPYRIGHT AND LICENSE
1116 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1117 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1118 redistribute it and/or modify it under the same terms as the
1119 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.