1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 use Scalar::Util qw/weaken blessed/;
14 DBIx::Class::Relationship::Base - Inter-table relationships
18 __PACKAGE__->add_relationship(
19 spiders => 'My::DB::Result::Creatures',
23 "$args->{foreign_alias}.id" => { -ident => "$args->{self_alias}.id" },
24 "$args->{foreign_alias}.type" => 'arachnid'
31 This class provides methods to describe the relationships between the
32 tables in your database model. These are the "bare bones" relationships
33 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
37 =head2 add_relationship
41 =item Arguments: $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 join-free condition hashref when
184 invoked as C<< $result->relationship >>, as opposed to
185 C<< $rs->related_resultset('relationship') >>. In this case C<$result> is
186 passed to the coderef as C<< $args->{self_rowobj} >>, so a user can do the
194 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
195 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
197 $args->{self_rowobj} && {
198 "$args->{foreign_alias}.artist" => $args->{self_rowobj}->artistid,
199 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
206 my $artist = $schema->resultset("Artist")->find({ id => 4 });
207 $artist->cds_80s->all;
209 Can skip a C<JOIN> altogether and instead produce:
211 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
213 WHERE cds_80s.artist = ?
217 With the bind values:
221 Note that in order to be able to use
222 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>,
223 the coderef must not only return as its second such a "simple" condition
224 hashref which does not depend on joins being available, but the hashref must
225 contain only plain values/deflatable objects, such that the result can be
226 passed directly to L<DBIx::Class::Relationship::Base/set_from_related>. For
227 instance the C<year> constraint in the above example prevents the relationship
228 from being used to create related objects (an exception will be thrown).
230 In order to allow the user to go truly crazy when generating a custom C<ON>
231 clause, the C<$args> hashref passed to the subroutine contains some extra
232 metadata. Currently the supplied coderef is executed as:
234 $relationship_info->{cond}->({
235 self_resultsource => The resultsource instance on which rel_name is registered
236 rel_name => The relationship name (does *NOT* always match foreign_alias)
238 self_alias => The alias of the invoking resultset
239 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
241 # only one of these (or none at all) will ever be supplied to aid in the
242 # construction of a join-free condition
243 self_resultobj => The invocant object itself in case of a $resultobj->$rel_name() call
244 foreign_resultobj => The related object in case of $resultobj->set_from_related($rel_name, $foreign_resultobj)
246 # deprecated inconsistent names, will be forever available for legacy code
247 self_rowobj => Old deprecated slot for self_resultobj
248 foreign_relname => Old deprecated slot for rel_name
253 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
254 be used as relationship attributes. In particular, the 'where' attribute is
255 useful for filtering relationships:
257 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
258 { 'foreign.user_id' => 'self.user_id' },
259 { where => { valid => 1 } }
262 The following attributes are also valid:
268 Explicitly specifies the type of join to use in the relationship. Any SQL
269 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
270 command immediately before C<JOIN>.
272 =item proxy =E<gt> $column | \@columns | \%column
274 The 'proxy' attribute can be used to retrieve values, and to perform
275 updates if the relationship has 'cascade_update' set. The 'might_have'
276 and 'has_one' relationships have this set by default; if you want a proxy
277 to update across a 'belongs_to' relationship, you must set the attribute
284 An arrayref containing a list of accessors in the foreign class to create in
285 the main class. If, for example, you do the following:
287 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
289 proxy => [ qw/notes/ ],
292 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
294 my $cd = MyApp::Schema::CD->find(1);
295 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
296 # created if it doesn't exist
298 For a 'belongs_to relationship, note the 'cascade_update':
300 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
301 { proxy => ['title'], cascade_update => 1 }
303 $track->title('New Title');
304 $track->update; # updates title in CD
308 A hashref where each key is the accessor you want installed in the main class,
309 and its value is the name of the original in the foreign class.
311 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
312 proxy => { cd_title => 'title' },
315 This will create an accessor named C<cd_title> on the C<$track> result object.
319 NOTE: you can pass a nested struct too, for example:
321 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
322 proxy => [ 'year', { cd_title => 'title' } ],
327 Specifies the type of accessor that should be created for the relationship.
328 Valid values are C<single> (for when there is only a single related object),
329 C<multi> (when there can be many), and C<filter> (for when there is a single
330 related object, but you also want the relationship accessor to double as
331 a column accessor). For C<multi> accessors, an add_to_* method is also
332 created, which calls C<create_related> for the relationship.
334 =item is_foreign_key_constraint
336 If you are using L<SQL::Translator> to create SQL for you and you find that it
337 is creating constraints where it shouldn't, or not creating them where it
338 should, set this attribute to a true or false value to override the detection
339 of when to create constraints.
343 If C<cascade_copy> is true on a C<has_many> relationship for an
344 object, then when you copy the object all the related objects will
345 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
346 in the C<$attr> hashref.
348 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
353 By default, DBIx::Class cascades deletes across C<has_many>,
354 C<has_one> and C<might_have> relationships. You can disable this
355 behaviour on a per-relationship basis by supplying
356 C<< cascade_delete => 0 >> in the relationship attributes.
358 The cascaded operations are performed after the requested delete,
359 so if your database has a constraint on the relationship, it will
360 have deleted/updated the related records or raised an exception
361 before DBIx::Class gets to perform the cascaded operation.
365 By default, DBIx::Class cascades updates across C<has_one> and
366 C<might_have> relationships. You can disable this behaviour on a
367 per-relationship basis by supplying C<< cascade_update => 0 >> in
368 the relationship attributes.
370 The C<belongs_to> relationship does not update across relationships
371 by default, so if you have a 'proxy' attribute on a belongs_to and want to
372 use 'update' on it, you muse set C<< cascade_update => 1 >>.
374 This is not a RDMS style cascade update - it purely means that when
375 an object has update called on it, all the related objects also
376 have update called. It will not change foreign keys automatically -
377 you must arrange to do this yourself.
379 =item on_delete / on_update
381 If you are using L<SQL::Translator> to create SQL for you, you can use these
382 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
383 type. If not supplied the SQLT parser will attempt to infer the constraint type by
384 interrogating the attributes of the B<opposite> relationship. For any 'multi'
385 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
386 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
387 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
388 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
389 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
390 C<< on_delete => '' >>, and the same for C<on_update> respectively.
394 Tells L<SQL::Translator> that the foreign key constraint it creates should be
395 deferrable. In other words, the user may request that the constraint be ignored
396 until the end of the transaction. Currently, only the PostgreSQL producer
397 actually supports this.
401 Tells L<SQL::Translator> to add an index for this constraint. Can also be
402 specified globally in the args to L<DBIx::Class::Schema/deploy> or
403 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
407 =head2 register_relationship
411 =item Arguments: $rel_name, $rel_info
415 Registers a relationship on the class. This is called internally by
416 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
420 sub register_relationship { }
422 =head2 related_resultset
426 =item Arguments: $rel_name
428 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
432 $rs = $cd->related_resultset('artist');
434 Returns a L<DBIx::Class::ResultSet> for the relationship named
437 =head2 $relationship_accessor
441 =item Arguments: none
443 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
447 # These pairs do the same thing
448 $result = $cd->related_resultset('artist')->single; # has_one relationship
449 $result = $cd->artist;
450 $rs = $cd->related_resultset('tracks'); # has_many relationship
453 This is the recommended way to traverse through relationships, based
454 on the L</accessor> name given in the relationship definition.
456 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
457 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
458 C<single> (returns only one row) or C<multi> (returns many rows). The
459 method may also return C<undef> if the relationship doesn't exist for
460 this instance (like in the case of C<might_have> relationships).
464 sub related_resultset {
467 $self->throw_exception("Can't call *_related as class methods")
472 return $self->{related_resultsets}{$rel}
473 if defined $self->{related_resultsets}{$rel};
475 return $self->{related_resultsets}{$rel} = do {
477 my $rel_info = $self->relationship_info($rel)
478 or $self->throw_exception( "No such relationship '$rel'" );
480 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
481 $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
483 $self->throw_exception( "Invalid query: @_" )
484 if (@_ > 1 && (@_ % 2 == 1));
485 my $query = ((@_ > 1) ? {@_} : shift);
487 my $rsrc = $self->result_source;
489 # condition resolution may fail if an incomplete master-object prefetch
490 # is encountered - that is ok during prefetch construction (not yet in_storage)
491 my ($cond, $is_crosstable) = try {
492 $rsrc->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel )
495 $self->throw_exception ($_) if $self->in_storage;
496 $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION; # RV, no return()
499 # keep in mind that the following if() block is part of a do{} - no return()s!!!
500 if ($is_crosstable and ref $rel_info->{cond} eq 'CODE') {
502 # A WHOREIFFIC hack to reinvoke the entire condition resolution
503 # with the correct alias. Another way of doing this involves a
504 # lot of state passing around, and the @_ positions are already
505 # mapped out, making this crap a less icky option.
507 # The point of this exercise is to retain the spirit of the original
508 # $obj->search_related($rel) where the resulting rset will have the
509 # root alias as 'me', instead of $rel (as opposed to invoking
510 # $rs->search_related)
512 local $rsrc->{_relationships}{me} = $rsrc->{_relationships}{$rel}; # make the fake 'me' rel
513 my $obj_table_alias = lc($rsrc->source_name) . '__row';
514 $obj_table_alias =~ s/\W+/_/g;
516 $rsrc->resultset->search(
517 $self->ident_condition($obj_table_alias),
518 { alias => $obj_table_alias },
519 )->search_related('me', $query, $attrs)
522 # FIXME - this conditional doesn't seem correct - got to figure out
523 # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
524 # business seems shady - we could simply not query *at all*
525 if ($cond eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
526 my $reverse = $rsrc->reverse_relationship_info($rel);
527 foreach my $rev_rel (keys %$reverse) {
528 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
529 weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
531 weaken($attrs->{related_objects}{$rev_rel} = $self);
535 elsif (ref $cond eq 'ARRAY') {
537 if (ref $_ eq 'HASH') {
539 foreach my $key (keys %$_) {
540 my $newkey = $key !~ /\./ ? "me.$key" : $key;
541 $hash->{$newkey} = $_->{$key};
549 elsif (ref $cond eq 'HASH') {
550 foreach my $key (grep { ! /\./ } keys %$cond) {
551 $cond->{"me.$key"} = delete $cond->{$key};
555 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
556 $rsrc->related_source($rel)->resultset->search(
563 =head2 search_related
567 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
569 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
573 Run a search on a related resultset. The search will be restricted to the
574 results represented by the L<DBIx::Class::ResultSet> it was called
577 See L<DBIx::Class::ResultSet/search_related> for more information.
582 return shift->related_resultset(shift)->search(@_);
585 =head2 search_related_rs
587 This method works exactly the same as search_related, except that
588 it guarantees a resultset, even in list context.
592 sub search_related_rs {
593 return shift->related_resultset(shift)->search_rs(@_);
600 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
602 =item Return Value: $count
606 Returns the count of all the rows in the related resultset, restricted by the
607 current result or where conditions.
612 shift->search_related(@_)->count;
619 =item Arguments: $rel_name, \%col_data
621 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
625 Create a new result object of the related foreign class. It will magically set
626 any foreign key columns of the new object to the related primary key columns
627 of the source object for you. The newly created result will not be saved into
628 your storage until you call L<DBIx::Class::Row/insert> on it.
633 my ($self, $rel, $values) = @_;
635 # FIXME - this is a bad position for this (also an identical copy in
636 # set_from_related), but I have no saner way to hook, and I absolutely
637 # want this to throw at least for coderefs, instead of the "insert a NULL
638 # when it gets hard" insanity --ribasushi
640 # sanity check - currently throw when a complex coderef rel is encountered
641 # FIXME - should THROW MOAR!
643 if (ref $self) { # cdbi calls this as a class method, /me vomits
645 my $rsrc = $self->result_source;
646 my $rel_info = $rsrc->relationship_info($rel)
647 or $self->throw_exception( "No such relationship '$rel'" );
648 my (undef, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
649 $rel_info->{cond}, $rel, $self, $rel
652 $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
656 $nonequality_foreign_columns
658 my @unspecified_rel_condition_chunks = grep { ! exists $values->{$_} } @$nonequality_foreign_columns
660 $self->throw_exception(sprintf (
661 "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
663 map { "'$_'" } @unspecified_rel_condition_chunks
668 return $self->search_related($rel)->new_result($values);
671 =head2 create_related
675 =item Arguments: $rel_name, \%col_data
677 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
681 my $result = $obj->create_related($rel_name, \%col_data);
683 Creates a new result object, similarly to new_related, and also inserts the
684 result's data into your storage medium. See the distinction between C<create>
685 and C<new> in L<DBIx::Class::ResultSet> for details.
692 my $obj = $self->new_related($rel, @_)->insert;
693 delete $self->{related_resultsets}->{$rel};
701 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
703 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
707 my $result = $obj->find_related($rel_name, \%col_data);
709 Attempt to find a related object using its primary key or unique constraints.
710 See L<DBIx::Class::ResultSet/find> for details.
715 #my ($self, $rel, @args) = @_;
716 return shift->search_related(shift)->find(@_);
719 =head2 find_or_new_related
723 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
725 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
729 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
734 sub find_or_new_related {
736 my $obj = $self->find_related(@_);
737 return defined $obj ? $obj : $self->new_related(@_);
740 =head2 find_or_create_related
744 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
746 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
750 Find or create a result object of a related class. See
751 L<DBIx::Class::ResultSet/find_or_create> for details.
755 sub find_or_create_related {
757 my $obj = $self->find_related(@_);
758 return (defined($obj) ? $obj : $self->create_related(@_));
761 =head2 update_or_create_related
765 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
767 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
771 Update or create a result object of a related class. See
772 L<DBIx::Class::ResultSet/update_or_create> for details.
776 sub update_or_create_related {
777 #my ($self, $rel, @args) = @_;
778 shift->related_resultset(shift)->update_or_create(@_);
781 =head2 set_from_related
785 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
787 =item Return Value: not defined
791 $book->set_from_related('author', $author_obj);
792 $book->author($author_obj); ## same thing
794 Set column values on the current object, using related values from the given
795 related object. This is used to associate previously separate objects, for
796 example, to set the correct author for a book, find the Author object, then
797 call set_from_related on the book.
799 This is called internally when you pass existing objects as values to
800 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
802 The columns are only set in the local copy of the object, call L</update> to
803 set them in the storage.
807 sub set_from_related {
808 my ($self, $rel, $f_obj) = @_;
810 my $rsrc = $self->result_source;
811 my $rel_info = $rsrc->relationship_info($rel)
812 or $self->throw_exception( "No such relationship '$rel'" );
814 if (defined $f_obj) {
815 my $f_class = $rel_info->{class};
816 $self->throw_exception( "Object '$f_obj' isn't a ".$f_class )
817 unless blessed $f_obj and $f_obj->isa($f_class);
821 # FIXME - this is a bad position for this (also an identical copy in
822 # new_related), but I have no saner way to hook, and I absolutely
823 # want this to throw at least for coderefs, instead of the "insert a NULL
824 # when it gets hard" insanity --ribasushi
826 # sanity check - currently throw when a complex coderef rel is encountered
827 # FIXME - should THROW MOAR!
828 my ($cond, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
829 $rel_info->{cond}, $f_obj, $rel, $rel
831 $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
834 $self->throw_exception(sprintf (
835 "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
837 map { "'$_'" } @$nonequality_foreign_columns
838 )) if $nonequality_foreign_columns;
840 $self->set_columns($cond);
845 =head2 update_from_related
849 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
851 =item Return Value: not defined
855 $book->update_from_related('author', $author_obj);
857 The same as L</"set_from_related">, but the changes are immediately updated
862 sub update_from_related {
864 $self->set_from_related(@_);
868 =head2 delete_related
872 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
874 =item Return Value: $underlying_storage_rv
878 Delete any related row, subject to the given conditions. Internally, this
881 $self->search_related(@_)->delete
883 And returns the result of that.
889 my $obj = $self->search_related(@_)->delete;
890 delete $self->{related_resultsets}->{$_[0]};
896 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
899 =head3 has_many / multi
903 =item Arguments: \%col_data
905 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
909 Creates/inserts a new result object. Internally, this calls:
911 $self->create_related($rel, @_)
913 And returns the result of that.
919 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
921 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
925 my $role = $schema->resultset('Role')->find(1);
926 $actor->add_to_roles($role);
927 # creates a My::DBIC::Schema::ActorRoles linking table result object
929 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
930 # creates a new My::DBIC::Schema::Role result object and the linking table
931 # object with an extra column in the link
933 Adds a linking table object. If the first argument is a hash reference, the
934 related object is created first with the column values in the hash. If an object
935 reference is given, just the linking table object is created. In either case,
936 any additional column values for the linking table object can be specified in
939 See L<DBIx::Class::Relationship/many_to_many> for additional details.
943 B<Currently only available for C<many_to_many> relationships.>
947 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
949 =item Return Value: not defined
953 my $actor = $schema->resultset('Actor')->find(1);
954 my @roles = $schema->resultset('Role')->search({ role =>
955 { '-in' => ['Fred', 'Barney'] } } );
957 $actor->set_roles(\@roles);
958 # Replaces all of $actor's previous roles with the two named
960 $actor->set_roles(\@roles, { salary => 15_000_000 });
961 # Sets a column in the link table for all roles
964 Replace all the related objects with the given reference to a list of
965 objects. This does a C<delete> B<on the link table resultset> to remove the
966 association between the current object and all related objects, then calls
967 C<add_to_$rel> repeatedly to link all the new objects.
969 Note that this means that this method will B<not> delete any objects in the
970 table on the right side of the relation, merely that it will delete the link
973 Due to a mistake in the original implementation of this method, it will also
974 accept a list of objects or hash references. This is B<deprecated> and will be
975 removed in a future version.
977 =head2 remove_from_$rel
979 B<Currently only available for C<many_to_many> relationships.>
983 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
985 =item Return Value: not defined
989 my $role = $schema->resultset('Role')->find(1);
990 $actor->remove_from_roles($role);
991 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
993 Removes the link between the current object and the related object. Note that
994 the related object itself won't be deleted unless you call ->delete() on
995 it. This method just removes the link between the two objects.
997 =head1 AUTHOR AND CONTRIBUTORS
999 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
1003 You may distribute this code under the same terms as Perl itself.