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( UNRESOLVABLE_CONDITION fail_on_internal_call );
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: $rel_name, $foreign_class, $condition, $attrs
45 __PACKAGE__->add_relationship('rel_name',
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 =head4 Simple equality
59 To create simple equality joins, supply a hashref containing the remote
60 table column name as the key(s) prefixed by C<'foreign.'>, and the
61 corresponding local table column name as the value(s) prefixed by C<'self.'>.
62 Both C<foreign> and C<self> are pseudo aliases and must be entered
63 literally. They will be replaced with the actual correct table alias
64 when the SQL is produced.
68 My::Schema::Author->has_many(
69 books => 'My::Schema::Book',
70 { 'foreign.author_id' => 'self.id' }
75 $author_rs->search_related('books')->next
77 will result in the following C<JOIN> clause:
79 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
81 This describes a relationship between the C<Author> table and the
82 C<Book> table where the C<Book> table has a column C<author_id>
83 containing the ID value of the C<Author>.
87 My::Schema::Book->has_many(
88 editions => 'My::Schema::Edition',
90 'foreign.publisher_id' => 'self.publisher_id',
91 'foreign.type_id' => 'self.type_id',
97 $book_rs->search_related('editions')->next
99 will result in the C<JOIN> clause:
102 LEFT JOIN edition editions ON
103 editions.publisher_id = me.publisher_id
104 AND editions.type_id = me.type_id ...
106 This describes the relationship from C<Book> to C<Edition>, where the
107 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
109 =head4 Multiple groups of simple equality conditions
111 As is the default in L<SQL::Abstract>, the key-value pairs will be
112 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
113 an arrayref. For example a condition like:
115 My::Schema::Item->has_many(
116 related_item_links => My::Schema::Item::Links,
118 { 'foreign.left_itemid' => 'self.id' },
119 { 'foreign.right_itemid' => 'self.id' },
123 will translate to the following C<JOIN> clause:
125 ... FROM item me JOIN item_relations related_item_links ON
126 related_item_links.left_itemid = me.id
127 OR related_item_links.right_itemid = me.id ...
129 This describes the relationship from C<Item> to C<Item::Links>, where
130 C<Item::Links> is a many-to-many linking table, linking items back to
131 themselves in a peer fashion (without a "parent-child" designation)
133 =head4 Custom join conditions
135 NOTE: The custom join condition specification mechanism is capable of
136 generating JOIN clauses of virtually unlimited complexity. This may limit
137 your ability to traverse some of the more involved relationship chains the
138 way you expect, *and* may bring your RDBMS to its knees. Exercise care
139 when declaring relationships as described here.
141 To specify joins which describe more than a simple equality of column
142 values, the custom join condition coderef syntax can be used. For
145 My::Schema::Artist->has_many(
146 cds_80s => 'My::Schema::CD',
151 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
152 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
159 $artist_rs->search_related('cds_80s')->next;
161 will result in the C<JOIN> clause:
163 ... FROM artist me LEFT JOIN cd cds_80s ON
164 cds_80s.artist = me.artistid
168 with the bind values:
172 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
173 same values that would be otherwise substituted for C<foreign> and C<self>
174 in the simple hashref syntax case.
176 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
177 like what one would supply as the first argument to
178 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
179 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
180 clause of the C<JOIN> statement associated with this relationship.
182 While every coderef-based condition must return a valid C<ON> clause, it may
183 elect to additionally return a simplified B<optional> join-free condition
184 consisting of a hashref with B<all keys being fully qualified names of columns
185 declared on the corresponding result source>. This boils down to two scenarios:
191 When relationship resolution is invoked after C<< $result->$rel_name >>, as
192 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
193 is passed to the coderef as C<< $args->{self_result_object} >>.
197 Alternatively when the user-space invokes resolution via
198 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
199 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
200 B<always> in the form of a hashref. If a foreign result object is supplied
201 (which is valid usage of L</set_from_related>), its values will be extracted
202 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
206 Note that the above scenarios are mutually exclusive, that is you will be supplied
207 none or only one of C<self_result_object> and C<foreign_values>. In other words if
208 you define your condition coderef as:
215 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
216 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
218 ! $args->{self_result_object} ? () : {
219 "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
220 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
222 ! $args->{foreign_values} ? () : {
223 "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
230 my $artist = $schema->resultset("Artist")->find({ id => 4 });
231 $artist->cds_80s->all;
233 Can skip a C<JOIN> altogether and instead produce:
235 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
237 WHERE cds_80s.artist = ?
241 With the bind values:
247 my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
248 my $artist = $schema->resultset("Artist")->new({});
249 $artist->set_from_related('cds_80s');
251 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
253 Note that in order to be able to use L</set_from_related> (and by extension
254 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
255 the returned join free condition B<must> contain only plain values/deflatable
256 objects. For instance the C<year> constraint in the above example prevents
257 the relationship from being used to create related objects using
258 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
259 exception will be thrown).
261 In order to allow the user to go truly crazy when generating a custom C<ON>
262 clause, the C<$args> hashref passed to the subroutine contains some extra
263 metadata. Currently the supplied coderef is executed as:
265 $relationship_info->{cond}->({
266 self_resultsource => The resultsource instance on which rel_name is registered
267 rel_name => The relationship name (does *NOT* always match foreign_alias)
269 self_alias => The alias of the invoking resultset
270 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
272 # only one of these (or none at all) will ever be supplied to aid in the
273 # construction of a join-free condition
275 self_result_object => The invocant *object* itself in case of a call like
276 $result_object->$rel_name( ... )
278 foreign_values => A *hashref* of related data: may be passed in directly or
279 derived via ->get_columns() from a related object in case of
280 $result_object->set_from_related( $rel_name, $foreign_result_object )
282 # deprecated inconsistent names, will be forever available for legacy code
283 self_rowobj => Old deprecated slot for self_result_object
284 foreign_relname => Old deprecated slot for rel_name
289 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
290 be used as relationship attributes. In particular, the 'where' attribute is
291 useful for filtering relationships:
293 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
294 { 'foreign.user_id' => 'self.user_id' },
295 { where => { valid => 1 } }
298 The following attributes are also valid:
304 Explicitly specifies the type of join to use in the relationship. Any SQL
305 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
306 command immediately before C<JOIN>.
308 =item proxy =E<gt> $column | \@columns | \%column
310 The 'proxy' attribute can be used to retrieve values, and to perform
311 updates if the relationship has 'cascade_update' set. The 'might_have'
312 and 'has_one' relationships have this set by default; if you want a proxy
313 to update across a 'belongs_to' relationship, you must set the attribute
320 An arrayref containing a list of accessors in the foreign class to create in
321 the main class. If, for example, you do the following:
323 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
325 proxy => [ qw/notes/ ],
328 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
330 my $cd = MyApp::Schema::CD->find(1);
331 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
332 # created if it doesn't exist
334 For a 'belongs_to relationship, note the 'cascade_update':
336 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
337 { proxy => ['title'], cascade_update => 1 }
339 $track->title('New Title');
340 $track->update; # updates title in CD
344 A hashref where each key is the accessor you want installed in the main class,
345 and its value is the name of the original in the foreign class.
347 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
348 proxy => { cd_title => 'title' },
351 This will create an accessor named C<cd_title> on the C<$track> result object.
355 NOTE: you can pass a nested struct too, for example:
357 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
358 proxy => [ 'year', { cd_title => 'title' } ],
363 Specifies the type of accessor that should be created for the relationship.
364 Valid values are C<single> (for when there is only a single related object),
365 C<multi> (when there can be many), and C<filter> (for when there is a single
366 related object, but you also want the relationship accessor to double as
367 a column accessor). For C<multi> accessors, an add_to_* method is also
368 created, which calls C<create_related> for the relationship.
370 =item is_foreign_key_constraint
372 If you are using L<SQL::Translator> to create SQL for you and you find that it
373 is creating constraints where it shouldn't, or not creating them where it
374 should, set this attribute to a true or false value to override the detection
375 of when to create constraints.
379 If C<cascade_copy> is true on a C<has_many> relationship for an
380 object, then when you copy the object all the related objects will
381 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
382 in the C<$attr> hashref.
384 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
389 By default, DBIx::Class cascades deletes across C<has_many>,
390 C<has_one> and C<might_have> relationships. You can disable this
391 behaviour on a per-relationship basis by supplying
392 C<< cascade_delete => 0 >> in the relationship attributes.
394 The cascaded operations are performed after the requested delete,
395 so if your database has a constraint on the relationship, it will
396 have deleted/updated the related records or raised an exception
397 before DBIx::Class gets to perform the cascaded operation.
401 By default, DBIx::Class cascades updates across C<has_one> and
402 C<might_have> relationships. You can disable this behaviour on a
403 per-relationship basis by supplying C<< cascade_update => 0 >> in
404 the relationship attributes.
406 The C<belongs_to> relationship does not update across relationships
407 by default, so if you have a 'proxy' attribute on a belongs_to and want to
408 use 'update' on it, you must set C<< cascade_update => 1 >>.
410 This is not a RDMS style cascade update - it purely means that when
411 an object has update called on it, all the related objects also
412 have update called. It will not change foreign keys automatically -
413 you must arrange to do this yourself.
415 =item on_delete / on_update
417 If you are using L<SQL::Translator> to create SQL for you, you can use these
418 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
419 type. If not supplied the SQLT parser will attempt to infer the constraint type by
420 interrogating the attributes of the B<opposite> relationship. For any 'multi'
421 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
422 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
423 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
424 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
425 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
426 C<< on_delete => '' >>, and the same for C<on_update> respectively.
430 Tells L<SQL::Translator> that the foreign key constraint it creates should be
431 deferrable. In other words, the user may request that the constraint be ignored
432 until the end of the transaction. Currently, only the PostgreSQL producer
433 actually supports this.
437 Tells L<SQL::Translator> to add an index for this constraint. Can also be
438 specified globally in the args to L<DBIx::Class::Schema/deploy> or
439 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
443 =head2 register_relationship
447 =item Arguments: $rel_name, $rel_info
451 Registers a relationship on the class. This is called internally by
452 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
456 sub register_relationship { }
458 =head2 related_resultset
462 =item Arguments: $rel_name
464 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
468 $rs = $cd->related_resultset('artist');
470 Returns a L<DBIx::Class::ResultSet> for the relationship named
473 =head2 $relationship_accessor
477 =item Arguments: none
479 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
483 # These pairs do the same thing
484 $result = $cd->related_resultset('artist')->single; # has_one relationship
485 $result = $cd->artist;
486 $rs = $cd->related_resultset('tracks'); # has_many relationship
489 This is the recommended way to traverse through relationships, based
490 on the L</accessor> name given in the relationship definition.
492 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
493 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
494 C<single> (returns only one row) or C<multi> (returns many rows). The
495 method may also return C<undef> if the relationship doesn't exist for
496 this instance (like in the case of C<might_have> relationships).
500 sub related_resultset {
501 $_[0]->throw_exception(
502 '$result->related_resultset() no longer accepts extra search arguments, '
503 . 'you need to switch to ...->related_resultset($relname)->search_rs(...) '
504 . 'instead (it was never documented and more importantly could never work '
505 . 'reliably due to the heavy caching involved)'
508 $_[0]->throw_exception("Can't call *_related as class methods")
511 return $_[0]->{related_resultsets}{$_[1]}
512 if defined $_[0]->{related_resultsets}{$_[1]};
514 my ($self, $rel) = @_;
516 return $self->{related_resultsets}{$rel} = do {
518 my $rsrc = $self->result_source;
520 my $rel_info = $rsrc->relationship_info($rel)
521 or $self->throw_exception( "No such relationship '$rel'" );
523 my $cond_res = $rsrc->_resolve_relationship_condition(
525 self_result_object => $self,
527 # this may look weird, but remember that we are making a resultset
528 # out of an existing object, with the new source being at the head
529 # of the FROM chain. Having a 'me' alias is nothing but expected there
530 foreign_alias => 'me',
532 self_alias => "!!!\xFF()!!!_SHOULD_NEVER_BE_SEEN_IN_USE_!!!()\xFF!!!",
534 # not strictly necessary, but shouldn't hurt either
535 require_join_free_condition => !!(ref $rel_info->{cond} ne 'CODE'),
538 # keep in mind that the following if() block is part of a do{} - no return()s!!!
540 ! $cond_res->{join_free_condition}
542 ref $rel_info->{cond} eq 'CODE'
545 # A WHOREIFFIC hack to reinvoke the entire condition resolution
546 # with the correct alias. Another way of doing this involves a
547 # lot of state passing around, and the @_ positions are already
548 # mapped out, making this crap a less icky option.
550 # The point of this exercise is to retain the spirit of the original
551 # $obj->search_related($rel) where the resulting rset will have the
552 # root alias as 'me', instead of $rel (as opposed to invoking
553 # $rs->search_related)
555 # make the fake 'me' rel
556 local $rsrc->{_relationships}{me} = {
557 %{ $rsrc->{_relationships}{$rel} },
558 _original_name => $rel,
561 my $obj_table_alias = lc($rsrc->source_name) . '__row';
562 $obj_table_alias =~ s/\W+/_/g;
564 $rsrc->resultset->search(
565 $self->ident_condition($obj_table_alias),
566 { alias => $obj_table_alias },
567 )->related_resultset('me')->search(undef, $rel_info->{attrs})
571 # FIXME - this conditional doesn't seem correct - got to figure out
572 # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
573 # business seems shady - we could simply not query *at all*
575 if ( $cond_res->{join_free_condition} eq UNRESOLVABLE_CONDITION ) {
576 $attrs = { %{$rel_info->{attrs}} };
577 my $reverse = $rsrc->reverse_relationship_info($rel);
578 foreach my $rev_rel (keys %$reverse) {
579 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
580 weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
582 weaken($attrs->{related_objects}{$rev_rel} = $self);
587 $rsrc->related_source($rel)->resultset->search(
588 $cond_res->{join_free_condition},
589 $attrs || $rel_info->{attrs},
595 =head2 search_related
599 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
601 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
605 Run a search on a related resultset. The search will be restricted to the
606 results represented by the L<DBIx::Class::ResultSet> it was called
609 See L<DBIx::Class::ResultSet/search_related> for more information.
613 sub search_related :DBIC_method_is_indirect_sugar {
614 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
615 shift->related_resultset(shift)->search(@_);
618 =head2 search_related_rs
620 This method works exactly the same as search_related, except that
621 it guarantees a resultset, even in list context.
625 sub search_related_rs :DBIC_method_is_indirect_sugar {
626 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
627 shift->related_resultset(shift)->search_rs(@_)
634 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
636 =item Return Value: $count
640 Returns the count of all the rows in the related resultset, restricted by the
641 current result or where conditions.
645 sub count_related :DBIC_method_is_indirect_sugar {
646 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
647 shift->related_resultset(shift)->search_rs(@_)->count;
654 =item Arguments: $rel_name, \%col_data
656 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
660 Create a new result object of the related foreign class. It will magically set
661 any foreign key columns of the new object to the related primary key columns
662 of the source object for you. The newly created result will not be saved into
663 your storage until you call L<DBIx::Class::Row/insert> on it.
668 my ($self, $rel, $data) = @_;
670 $self->related_resultset($rel)->new_result( $self->result_source->_resolve_relationship_condition (
671 infer_values_based_on => $data,
673 self_result_object => $self,
674 foreign_alias => $rel,
676 )->{inferred_values} );
679 =head2 create_related
683 =item Arguments: $rel_name, \%col_data
685 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
689 my $result = $obj->create_related($rel_name, \%col_data);
691 Creates a new result object, similarly to new_related, and also inserts the
692 result's data into your storage medium. See the distinction between C<create>
693 and C<new> in L<DBIx::Class::ResultSet> for details.
700 my $obj = $self->new_related($rel, @_)->insert;
701 delete $self->{related_resultsets}->{$rel};
709 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
711 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
715 my $result = $obj->find_related($rel_name, \%col_data);
717 Attempt to find a related object using its primary key or unique constraints.
718 See L<DBIx::Class::ResultSet/find> for details.
722 sub find_related :DBIC_method_is_indirect_sugar {
723 #my ($self, $rel, @args) = @_;
724 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
725 return shift->related_resultset(shift)->find(@_);
728 =head2 find_or_new_related
732 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
734 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
738 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
743 sub find_or_new_related {
746 my $obj = $self->related_resultset($rel)->find(@_);
747 return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
750 =head2 find_or_create_related
754 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
756 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
760 Find or create a result object of a related class. See
761 L<DBIx::Class::ResultSet/find_or_create> for details.
765 sub find_or_create_related {
768 my $obj = $self->related_resultset($rel)->find(@_);
769 return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
772 =head2 update_or_create_related
776 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
778 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
782 Update or create a result object of a related class. See
783 L<DBIx::Class::ResultSet/update_or_create> for details.
787 sub update_or_create_related :DBIC_method_is_indirect_sugar {
788 #my ($self, $rel, @args) = @_;
789 DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
790 shift->related_resultset(shift)->update_or_create(@_);
793 =head2 set_from_related
797 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
799 =item Return Value: not defined
803 $book->set_from_related('author', $author_obj);
804 $book->author($author_obj); ## same thing
806 Set column values on the current object, using related values from the given
807 related object. This is used to associate previously separate objects, for
808 example, to set the correct author for a book, find the Author object, then
809 call set_from_related on the book.
811 This is called internally when you pass existing objects as values to
812 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
814 The columns are only set in the local copy of the object, call
815 L<update|DBIx::Class::Row/update> to update them in the storage.
819 sub set_from_related {
820 my ($self, $rel, $f_obj) = @_;
822 $self->set_columns( $self->result_source->_resolve_relationship_condition (
823 infer_values_based_on => {},
825 foreign_values => $f_obj,
826 foreign_alias => $rel,
828 )->{inferred_values} );
833 =head2 update_from_related
837 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
839 =item Return Value: not defined
843 $book->update_from_related('author', $author_obj);
845 The same as L</"set_from_related">, but the changes are immediately updated
850 sub update_from_related {
852 $self->set_from_related(@_);
856 =head2 delete_related
860 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
862 =item Return Value: $underlying_storage_rv
866 Delete any related row, subject to the given conditions. Internally, this
869 $self->search_related(@_)->delete
871 And returns the result of that.
878 my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
879 delete $self->{related_resultsets}->{$rel};
885 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
888 =head3 has_many / multi
892 =item Arguments: \%col_data
894 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
898 Creates/inserts a new result object. Internally, this calls:
900 $self->create_related($rel, @_)
902 And returns the result of that.
908 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
910 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
914 my $role = $schema->resultset('Role')->find(1);
915 $actor->add_to_roles($role);
916 # creates a My::DBIC::Schema::ActorRoles linking table result object
918 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
919 # creates a new My::DBIC::Schema::Role result object and the linking table
920 # object with an extra column in the link
922 Adds a linking table object. If the first argument is a hash reference, the
923 related object is created first with the column values in the hash. If an object
924 reference is given, just the linking table object is created. In either case,
925 any additional column values for the linking table object can be specified in
928 See L<DBIx::Class::Relationship/many_to_many> for additional details.
932 B<Currently only available for C<many_to_many> relationships.>
936 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
938 =item Return Value: not defined
942 my $actor = $schema->resultset('Actor')->find(1);
943 my @roles = $schema->resultset('Role')->search({ role =>
944 { '-in' => ['Fred', 'Barney'] } } );
946 $actor->set_roles(\@roles);
947 # Replaces all of $actor's previous roles with the two named
949 $actor->set_roles(\@roles, { salary => 15_000_000 });
950 # Sets a column in the link table for all roles
953 Replace all the related objects with the given reference to a list of
954 objects. This does a C<delete> B<on the link table resultset> to remove the
955 association between the current object and all related objects, then calls
956 C<add_to_$rel> repeatedly to link all the new objects.
958 Note that this means that this method will B<not> delete any objects in the
959 table on the right side of the relation, merely that it will delete the link
962 Due to a mistake in the original implementation of this method, it will also
963 accept a list of objects or hash references. This is B<deprecated> and will be
964 removed in a future version.
966 =head2 remove_from_$rel
968 B<Currently only available for C<many_to_many> relationships.>
972 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
974 =item Return Value: not defined
978 my $role = $schema->resultset('Role')->find(1);
979 $actor->remove_from_roles($role);
980 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
982 Removes the link between the current object and the related object. Note that
983 the related object itself won't be deleted unless you call ->delete() on
984 it. This method just removes the link between the two objects.
986 =head1 FURTHER QUESTIONS?
988 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
990 =head1 COPYRIGHT AND LICENSE
992 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
993 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
994 redistribute it and/or modify it under the same terms as the
995 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.