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 dbic_internal_catch fail_on_internal_call
13 use DBIx::Class::SQLMaker::Util 'extract_equality_conditions';
14 use DBIx::Class::Carp;
16 # FIXME - this should go away
17 # instead Carp::Skip should export usable keywords or something like that
19 BEGIN { $unique_carper = \&carp_unique }
25 DBIx::Class::Relationship::Base - Inter-table relationships
29 __PACKAGE__->add_relationship(
30 spiders => 'My::DB::Result::Creatures',
34 "$args->{foreign_alias}.id" => { -ident => "$args->{self_alias}.id" },
35 "$args->{foreign_alias}.type" => 'arachnid'
42 This class provides methods to describe the relationships between the
43 tables in your database model. These are the "bare bones" relationships
44 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
48 =head2 add_relationship
52 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
56 __PACKAGE__->add_relationship('rel_name',
60 Create a custom relationship between one result source and another
61 source, indicated by its class name.
65 The condition argument describes the C<ON> clause of the C<JOIN>
66 expression used to connect the two sources when creating SQL queries.
68 =head4 Simple equality
70 To create simple equality joins, supply a hashref containing the remote
71 table column name as the key(s) prefixed by C<'foreign.'>, and the
72 corresponding local table column name as the value(s) prefixed by C<'self.'>.
73 Both C<foreign> and C<self> are pseudo aliases and must be entered
74 literally. They will be replaced with the actual correct table alias
75 when the SQL is produced.
79 My::Schema::Author->has_many(
80 books => 'My::Schema::Book',
81 { 'foreign.author_id' => 'self.id' }
86 $author_rs->search_related('books')->next
88 will result in the following C<JOIN> clause:
90 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
92 This describes a relationship between the C<Author> table and the
93 C<Book> table where the C<Book> table has a column C<author_id>
94 containing the ID value of the C<Author>.
98 My::Schema::Book->has_many(
99 editions => 'My::Schema::Edition',
101 'foreign.publisher_id' => 'self.publisher_id',
102 'foreign.type_id' => 'self.type_id',
108 $book_rs->search_related('editions')->next
110 will result in the C<JOIN> clause:
113 LEFT JOIN edition editions ON
114 editions.publisher_id = me.publisher_id
115 AND editions.type_id = me.type_id ...
117 This describes the relationship from C<Book> to C<Edition>, where the
118 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
120 =head4 Multiple groups of simple equality conditions
122 As is the default in L<SQL::Abstract>, the key-value pairs will be
123 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
124 an arrayref. For example a condition like:
126 My::Schema::Item->has_many(
127 related_item_links => My::Schema::Item::Links,
129 { 'foreign.left_itemid' => 'self.id' },
130 { 'foreign.right_itemid' => 'self.id' },
134 will translate to the following C<JOIN> clause:
136 ... FROM item me JOIN item_relations related_item_links ON
137 related_item_links.left_itemid = me.id
138 OR related_item_links.right_itemid = me.id ...
140 This describes the relationship from C<Item> to C<Item::Links>, where
141 C<Item::Links> is a many-to-many linking table, linking items back to
142 themselves in a peer fashion (without a "parent-child" designation)
144 =head4 Custom join conditions
146 NOTE: The custom join condition specification mechanism is capable of
147 generating JOIN clauses of virtually unlimited complexity. This may limit
148 your ability to traverse some of the more involved relationship chains the
149 way you expect, *and* may bring your RDBMS to its knees. Exercise care
150 when declaring relationships as described here.
152 To specify joins which describe more than a simple equality of column
153 values, the custom join condition coderef syntax can be used. For
156 My::Schema::Artist->has_many(
157 cds_80s => 'My::Schema::CD',
162 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
163 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
170 $artist_rs->search_related('cds_80s')->next;
172 will result in the C<JOIN> clause:
174 ... FROM artist me LEFT JOIN cd cds_80s ON
175 cds_80s.artist = me.artistid
179 with the bind values:
183 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
184 same values that would be otherwise substituted for C<foreign> and C<self>
185 in the simple hashref syntax case.
187 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
188 like what one would supply as the first argument to
189 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
190 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
191 clause of the C<JOIN> statement associated with this relationship.
193 While every coderef-based condition must return a valid C<ON> clause, it may
194 elect to additionally return a simplified B<optional> join-free condition
195 consisting of a hashref with B<all keys being fully qualified names of columns
196 declared on the corresponding result source>. This boils down to two scenarios:
202 When relationship resolution is invoked after C<< $result->$rel_name >>, as
203 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
204 is passed to the coderef as C<< $args->{self_result_object} >>.
208 Alternatively when the user-space invokes resolution via
209 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
210 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
211 B<always> in the form of a hashref. If a foreign result object is supplied
212 (which is valid usage of L</set_from_related>), its values will be extracted
213 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
217 Note that the above scenarios are mutually exclusive, that is you will be supplied
218 none or only one of C<self_result_object> and C<foreign_values>. In other words if
219 you define your condition coderef as:
226 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
227 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
229 ! $args->{self_result_object} ? () : {
230 "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
231 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
233 ! $args->{foreign_values} ? () : {
234 "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
241 my $artist = $schema->resultset("Artist")->find({ id => 4 });
242 $artist->cds_80s->all;
244 Can skip a C<JOIN> altogether and instead produce:
246 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
248 WHERE cds_80s.artist = ?
252 With the bind values:
258 my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
259 my $artist = $schema->resultset("Artist")->new({});
260 $artist->set_from_related('cds_80s');
262 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
264 Note that in order to be able to use L</set_from_related> (and by extension
265 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
266 the returned join free condition B<must> contain only plain values/deflatable
267 objects. For instance the C<year> constraint in the above example prevents
268 the relationship from being used to create related objects using
269 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
270 exception will be thrown).
272 In order to allow the user to go truly crazy when generating a custom C<ON>
273 clause, the C<$args> hashref passed to the subroutine contains some extra
274 metadata. Currently the supplied coderef is executed as:
276 $relationship_info->{cond}->({
277 self_resultsource => The resultsource instance on which rel_name is registered
278 rel_name => The relationship name (does *NOT* always match foreign_alias)
280 self_alias => The alias of the invoking resultset
281 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
283 # only one of these (or none at all) will ever be supplied to aid in the
284 # construction of a join-free condition
286 self_result_object => The invocant *object* itself in case of a call like
287 $result_object->$rel_name( ... )
289 foreign_values => A *hashref* of related data: may be passed in directly or
290 derived via ->get_columns() from a related object in case of
291 $result_object->set_from_related( $rel_name, $foreign_result_object )
293 # deprecated inconsistent names, will be forever available for legacy code
294 self_rowobj => Old deprecated slot for self_result_object
295 foreign_relname => Old deprecated slot for rel_name
300 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
301 be used as relationship attributes. In particular, the 'where' attribute is
302 useful for filtering relationships:
304 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
305 { 'foreign.user_id' => 'self.user_id' },
306 { where => { valid => 1 } }
309 The following attributes are also valid:
315 Explicitly specifies the type of join to use in the relationship. Any SQL
316 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
317 command immediately before C<JOIN>.
319 =item proxy =E<gt> $column | \@columns | \%column
321 The 'proxy' attribute can be used to retrieve values, and to perform
322 updates if the relationship has 'cascade_update' set. The 'might_have'
323 and 'has_one' relationships have this set by default; if you want a proxy
324 to update across a 'belongs_to' relationship, you must set the attribute
331 An arrayref containing a list of accessors in the foreign class to create in
332 the main class. If, for example, you do the following:
334 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
336 proxy => [ qw/notes/ ],
339 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
341 my $cd = MyApp::Schema::CD->find(1);
342 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
343 # created if it doesn't exist
345 For a 'belongs_to relationship, note the 'cascade_update':
347 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
348 { proxy => ['title'], cascade_update => 1 }
350 $track->title('New Title');
351 $track->update; # updates title in CD
355 A hashref where each key is the accessor you want installed in the main class,
356 and its value is the name of the original in the foreign class.
358 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
359 proxy => { cd_title => 'title' },
362 This will create an accessor named C<cd_title> on the C<$track> result object.
366 NOTE: you can pass a nested struct too, for example:
368 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
369 proxy => [ 'year', { cd_title => 'title' } ],
374 Specifies the type of accessor that should be created for the relationship.
375 Valid values are C<single> (for when there is only a single related object),
376 C<multi> (when there can be many), and C<filter> (for when there is a single
377 related object, but you also want the relationship accessor to double as
378 a column accessor). For C<multi> accessors, an add_to_* method is also
379 created, which calls C<create_related> for the relationship.
381 =item is_foreign_key_constraint
383 If you are using L<SQL::Translator> to create SQL for you and you find that it
384 is creating constraints where it shouldn't, or not creating them where it
385 should, set this attribute to a true or false value to override the detection
386 of when to create constraints.
390 If C<cascade_copy> is true on a C<has_many> relationship for an
391 object, then when you copy the object all the related objects will
392 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
393 in the C<$attr> hashref.
395 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
400 By default, DBIx::Class cascades deletes across C<has_many>,
401 C<has_one> and C<might_have> relationships. You can disable this
402 behaviour on a per-relationship basis by supplying
403 C<< cascade_delete => 0 >> in the relationship attributes.
405 The cascaded operations are performed after the requested delete,
406 so if your database has a constraint on the relationship, it will
407 have deleted/updated the related records or raised an exception
408 before DBIx::Class gets to perform the cascaded operation.
412 By default, DBIx::Class cascades updates across C<has_one> and
413 C<might_have> relationships. You can disable this behaviour on a
414 per-relationship basis by supplying C<< cascade_update => 0 >> in
415 the relationship attributes.
417 The C<belongs_to> relationship does not update across relationships
418 by default, so if you have a 'proxy' attribute on a belongs_to and want to
419 use 'update' on it, you must set C<< cascade_update => 1 >>.
421 This is not a RDMS style cascade update - it purely means that when
422 an object has update called on it, all the related objects also
423 have update called. It will not change foreign keys automatically -
424 you must arrange to do this yourself.
426 =item on_delete / on_update
428 If you are using L<SQL::Translator> to create SQL for you, you can use these
429 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
430 type. If not supplied the SQLT parser will attempt to infer the constraint type by
431 interrogating the attributes of the B<opposite> relationship. For any 'multi'
432 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
433 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
434 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
435 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
436 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
437 C<< on_delete => '' >>, and the same for C<on_update> respectively.
441 Tells L<SQL::Translator> that the foreign key constraint it creates should be
442 deferrable. In other words, the user may request that the constraint be ignored
443 until the end of the transaction. Currently, only the PostgreSQL producer
444 actually supports this.
448 Tells L<SQL::Translator> to add an index for this constraint. Can also be
449 specified globally in the args to L<DBIx::Class::Schema/deploy> or
450 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
454 =head2 register_relationship
458 =item Arguments: $rel_name, $rel_info
462 Registers a relationship on the class. This is called internally by
463 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
467 sub register_relationship { }
469 =head2 related_resultset
473 =item Arguments: $rel_name
475 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
479 $rs = $cd->related_resultset('artist');
481 Returns a L<DBIx::Class::ResultSet> for the relationship named
484 =head2 $relationship_accessor
488 =item Arguments: none
490 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
494 # These pairs do the same thing
495 $result = $cd->related_resultset('artist')->single; # has_one relationship
496 $result = $cd->artist;
497 $rs = $cd->related_resultset('tracks'); # has_many relationship
500 This is the recommended way to traverse through relationships, based
501 on the L</accessor> name given in the relationship definition.
503 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
504 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
505 C<single> (returns only one row) or C<multi> (returns many rows). The
506 method may also return C<undef> if the relationship doesn't exist for
507 this instance (like in the case of C<might_have> relationships).
511 sub related_resultset {
512 $_[0]->throw_exception(
513 '$result->related_resultset() no longer accepts extra search arguments, '
514 . 'you need to switch to ...->related_resultset($relname)->search_rs(...) '
515 . 'instead (it was never documented and more importantly could never work '
516 . 'reliably due to the heavy caching involved)'
519 $_[0]->throw_exception("Can't call *_related as class methods")
522 return $_[0]->{related_resultsets}{$_[1]}
523 if defined $_[0]->{related_resultsets}{$_[1]};
525 my ($self, $rel) = @_;
527 my $rsrc = $self->result_source;
529 my $rel_info = $rsrc->relationship_info($rel)
530 or $self->throw_exception( "No such relationship '$rel'" );
532 my $relcond_is_freeform = ref $rel_info->{cond} eq 'CODE';
536 self_result_object => $self,
538 # an extra sanity check guard
539 require_join_free_condition => !!(
540 ! $relcond_is_freeform
545 # an API where these are optional would be too cumbersome,
546 # instead always pass in some dummy values
549 # this may look weird, but remember that we are making a resultset
550 # out of an existing object, with the new source being at the head
551 # of the FROM chain. Having a 'me' alias is nothing but expected there
552 foreign_alias => 'me',
556 # In certain extraordinary circumstances the relationship resolution may
557 # throw (e.g. when walking through elaborate custom conds)
558 # In case the object is "real" (i.e. in_storage) we just go ahead and
559 # let the exception surface. Otherwise we carp and move on.
561 # The elaborate code-duplicating ternary is there because the xsified
562 # ->in_storage() is orders of magnitude faster than the Try::Tiny-like
563 # construct below ( perl's low level tooling is truly shit :/ )
564 ( $self->in_storage or DBIx::Class::_Util::in_internal_try )
565 ? $rsrc->resolve_relationship_condition($rrc_args)->{join_free_condition}
566 : dbic_internal_try {
567 $rsrc->resolve_relationship_condition($rrc_args)->{join_free_condition}
569 dbic_internal_catch {
571 "Resolution of relationship '$rel' failed unexpectedly, "
572 . 'please relay the following error and seek assistance via '
573 . DBIx::Class::_ENV_::HELP_URL . ". Encountered error: $_"
576 # FIXME - this is questionable
577 # force skipping re-resolution, and instead just return an UC rset
578 $relcond_is_freeform = 0;
589 $rel_rset = $rsrc->related_source($rel)->resultset->search_rs(
594 elsif( $relcond_is_freeform ) {
596 # A WHOREIFFIC hack to reinvoke the entire condition resolution
597 # with the correct alias. Another way of doing this involves a
598 # lot of state passing around, and the @_ positions are already
599 # mapped out, making this crap a less icky option.
601 # The point of this exercise is to retain the spirit of the original
602 # $obj->search_related($rel) where the resulting rset will have the
603 # root alias as 'me', instead of $rel (as opposed to invoking
604 # $rs->search_related)
606 # make the fake 'me' rel
607 local $rsrc->{_relationships}{me} = {
608 %{ $rsrc->{_relationships}{$rel} },
609 _original_name => $rel,
612 my $obj_table_alias = lc($rsrc->source_name) . '__row';
613 $obj_table_alias =~ s/\W+/_/g;
615 $rel_rset = $rsrc->resultset->search_rs(
616 $self->ident_condition($obj_table_alias),
617 { alias => $obj_table_alias },
618 )->related_resultset('me')->search_rs(undef, $rel_info->{attrs})
622 my $attrs = { %{$rel_info->{attrs}} };
623 my $reverse = $rsrc->reverse_relationship_info($rel);
625 # FIXME - this loop doesn't seem correct - got to figure out
626 # at some point what exactly it does.
627 # See also the FIXME at the end of new_related()
628 ( ( $reverse->{$_}{attrs}{accessor}||'') eq 'multi' )
629 ? weaken( $attrs->{related_objects}{$_}[0] = $self )
630 : weaken( $attrs->{related_objects}{$_} = $self )
633 $rel_rset = $rsrc->related_source($rel)->resultset->search_rs(
634 UNRESOLVABLE_CONDITION, # guards potential use of the $rs in the future
639 $self->{related_resultsets}{$rel} = $rel_rset;
642 =head2 search_related
646 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
648 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
652 Run a search on a related resultset. The search will be restricted to the
653 results represented by the L<DBIx::Class::ResultSet> it was called
656 See L<DBIx::Class::ResultSet/search_related> for more information.
660 sub search_related :DBIC_method_is_indirect_sugar {
661 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
662 shift->related_resultset(shift)->search(@_);
665 =head2 search_related_rs
667 This method works exactly the same as search_related, except that
668 it guarantees a resultset, even in list context.
672 sub search_related_rs :DBIC_method_is_indirect_sugar {
673 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
674 shift->related_resultset(shift)->search_rs(@_)
681 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
683 =item Return Value: $count
687 Returns the count of all the rows in the related resultset, restricted by the
688 current result or where conditions.
692 sub count_related :DBIC_method_is_indirect_sugar {
693 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
694 shift->related_resultset(shift)->search_rs(@_)->count;
701 =item Arguments: $rel_name, \%col_data
703 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
707 Create a new result object of the related foreign class. It will magically set
708 any foreign key columns of the new object to the related primary key columns
709 of the source object for you. The newly created result will not be saved into
710 your storage until you call L<DBIx::Class::Row/insert> on it.
715 my ($self, $rel, $data) = @_;
717 $self->throw_exception(
718 "Result object instantiation requires a hashref as argument"
719 ) unless ref $data eq 'HASH';
721 my $rsrc = $self->result_source;
722 my $rel_rsrc = $rsrc->related_source($rel);
725 ### This section deliberately does not rely on require_join_free_values,
726 ### as quite often the resulting related object is useless without the
727 ### contents of $data mixed in. Originally this code was part of
728 ### resolve_relationship_condition() but given it has a single, very
729 ### context-specific call-site it made no sense to expose it to end users.
732 my $rel_resolution = $rsrc->resolve_relationship_condition (
734 self_result_object => $self,
736 # In case we are *not* in_storage it is ok to treat failed resolution as an empty hash
737 # This happens e.g. as a result of various in-memory related graph of objects
738 require_join_free_condition => !! $self->in_storage,
740 # dummy aliases with deliberately known lengths, so that we can
741 # quickly strip them below if needed
742 foreign_alias => 'F',
747 $rel_resolution->{join_free_values}
749 { map { substr( $_, 2 ) => $rel_resolution->{join_free_condition}{$_} } keys %{ $rel_resolution->{join_free_condition} } }
752 # mix everything together
753 my $amalgamated_values = {
755 # in case we got back join_free_values - they already have passed the extractor
756 $rel_resolution->{join_free_values}
758 : extract_equality_conditions(
766 # cleanup possible rogue { somecolumn => [ -and => 1,2 ] }
767 ($amalgamated_values->{$_}||'') eq UNRESOLVABLE_CONDITION
769 delete $amalgamated_values->{$_}
770 for keys %$amalgamated_values;
772 if( my @nonvalues = grep { ! exists $amalgamated_values->{$_} } keys %$rel_values ) {
774 $self->throw_exception(
775 "Unable to complete value inferrence - relationship '$rel' "
776 . "on source '@{[ $rsrc->source_name ]}' results "
777 . 'in expression(s) instead of definitive values: '
779 # FIXME - used for diag only, but still icky
781 dbic_internal_try { $rsrc->schema->storage->sql_maker }
784 require DBIx::Class::SQLMaker
786 DBIx::Class::SQLMaker->new
789 local $sqlm->{quote_char};
790 local $sqlm->{_dequalify_idents} = 1;
791 ($sqlm->_recurse_where({ map { $_ => $rel_values->{$_} } @nonvalues }))[0]
796 # And more complications - in case the relationship did not resolve
797 # we *have* to loop things through search_related ( essentially re-resolving
798 # everything we did so far, but with different type of handholding )
799 # FIXME - this is still a mess, just a *little* better than it was
800 # See also the FIXME at the end of related_resultset()
801 exists $rel_resolution->{join_free_values}
802 ? $rel_rsrc->result_class->new({ -result_source => $rel_rsrc, %$amalgamated_values })
803 : $self->related_resultset($rel)->new_result( $amalgamated_values )
807 =head2 create_related
811 =item Arguments: $rel_name, \%col_data
813 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
817 my $result = $obj->create_related($rel_name, \%col_data);
819 Creates a new result object, similarly to new_related, and also inserts the
820 result's data into your storage medium. See the distinction between C<create>
821 and C<new> in L<DBIx::Class::ResultSet> for details.
828 my $obj = $self->new_related($rel, @_)->insert;
829 delete $self->{related_resultsets}->{$rel};
837 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
839 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
843 my $result = $obj->find_related($rel_name, \%col_data);
845 Attempt to find a related object using its primary key or unique constraints.
846 See L<DBIx::Class::ResultSet/find> for details.
850 sub find_related :DBIC_method_is_indirect_sugar {
851 #my ($self, $rel, @args) = @_;
852 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
853 return shift->related_resultset(shift)->find(@_);
856 =head2 find_or_new_related
860 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
862 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
866 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
871 sub find_or_new_related {
874 my $obj = $self->related_resultset($rel)->find(@_);
875 return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
878 =head2 find_or_create_related
882 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
884 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
888 Find or create a result object of a related class. See
889 L<DBIx::Class::ResultSet/find_or_create> for details.
893 sub find_or_create_related {
896 my $obj = $self->related_resultset($rel)->find(@_);
897 return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
900 =head2 update_or_create_related
904 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
906 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
910 Update or create a result object of a related class. See
911 L<DBIx::Class::ResultSet/update_or_create> for details.
915 sub update_or_create_related :DBIC_method_is_indirect_sugar {
916 #my ($self, $rel, @args) = @_;
917 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
918 shift->related_resultset(shift)->update_or_create(@_);
921 =head2 set_from_related
925 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
927 =item Return Value: not defined
931 $book->set_from_related('author', $author_obj);
932 $book->author($author_obj); ## same thing
934 Set column values on the current object, using related values from the given
935 related object. This is used to associate previously separate objects, for
936 example, to set the correct author for a book, find the Author object, then
937 call set_from_related on the book.
939 This is called internally when you pass existing objects as values to
940 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
942 The columns are only set in the local copy of the object, call
943 L<update|DBIx::Class::Row/update> to update them in the storage.
947 sub set_from_related {
948 my ($self, $rel, $f_obj) = @_;
950 $self->set_columns( $self->result_source->resolve_relationship_condition (
951 require_join_free_values => 1,
954 # maintain crazy set_from_related interface
956 ( ! defined $f_obj ) ? +{}
957 : ( ! defined blessed $f_obj ) ? $f_obj
960 my $f_result_class = $self->result_source->related_source($rel)->result_class;
962 unless( $f_obj->isa($f_result_class) ) {
964 $self->throw_exception(
965 'Object supplied to set_from_related() must inherit from '
966 . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
967 ) unless $f_obj->isa(
968 $DBIx::Class::ResultSource::__expected_result_class_isa
972 'Object supplied to set_from_related() usually should inherit from '
973 . "the related ResultClass ('$f_result_class'), perhaps you've made "
978 +{ $f_obj->get_columns };
982 # an API where these are optional would be too cumbersome,
983 # instead always pass in some dummy values
986 )->{join_free_values} );
991 =head2 update_from_related
995 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
997 =item Return Value: not defined
1001 $book->update_from_related('author', $author_obj);
1003 The same as L</"set_from_related">, but the changes are immediately updated
1008 sub update_from_related {
1010 $self->set_from_related(@_);
1014 =head2 delete_related
1018 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
1020 =item Return Value: $underlying_storage_rv
1024 Delete any related row, subject to the given conditions. Internally, this
1027 $self->search_related(@_)->delete
1029 And returns the result of that.
1033 sub delete_related {
1036 my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
1037 delete $self->{related_resultsets}->{$rel};
1043 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
1046 =head3 has_many / multi
1050 =item Arguments: \%col_data
1052 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1056 Creates/inserts a new result object. Internally, this calls:
1058 $self->create_related($rel, @_)
1060 And returns the result of that.
1066 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
1068 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
1072 my $role = $schema->resultset('Role')->find(1);
1073 $actor->add_to_roles($role);
1074 # creates a My::DBIC::Schema::ActorRoles linking table result object
1076 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
1077 # creates a new My::DBIC::Schema::Role result object and the linking table
1078 # object with an extra column in the link
1080 Adds a linking table object. If the first argument is a hash reference, the
1081 related object is created first with the column values in the hash. If an object
1082 reference is given, just the linking table object is created. In either case,
1083 any additional column values for the linking table object can be specified in
1086 See L<DBIx::Class::Relationship/many_to_many> for additional details.
1090 B<Currently only available for C<many_to_many> relationships.>
1094 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
1096 =item Return Value: not defined
1100 my $actor = $schema->resultset('Actor')->find(1);
1101 my @roles = $schema->resultset('Role')->search({ role =>
1102 { '-in' => ['Fred', 'Barney'] } } );
1104 $actor->set_roles(\@roles);
1105 # Replaces all of $actor's previous roles with the two named
1107 $actor->set_roles(\@roles, { salary => 15_000_000 });
1108 # Sets a column in the link table for all roles
1111 Replace all the related objects with the given reference to a list of
1112 objects. This does a C<delete> B<on the link table resultset> to remove the
1113 association between the current object and all related objects, then calls
1114 C<add_to_$rel> repeatedly to link all the new objects.
1116 Note that this means that this method will B<not> delete any objects in the
1117 table on the right side of the relation, merely that it will delete the link
1120 Due to a mistake in the original implementation of this method, it will also
1121 accept a list of objects or hash references. This is B<deprecated> and will be
1122 removed in a future version.
1124 =head2 remove_from_$rel
1126 B<Currently only available for C<many_to_many> relationships.>
1130 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
1132 =item Return Value: not defined
1136 my $role = $schema->resultset('Role')->find(1);
1137 $actor->remove_from_roles($role);
1138 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
1140 Removes the link between the current object and the related object. Note that
1141 the related object itself won't be deleted unless you call ->delete() on
1142 it. This method just removes the link between the two objects.
1144 =head1 FURTHER QUESTIONS?
1146 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1148 =head1 COPYRIGHT AND LICENSE
1150 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1151 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1152 redistribute it and/or modify it under the same terms as the
1153 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.