1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 use Scalar::Util qw/weaken blessed/;
10 use DBIx::Class::_Util 'UNRESOLVABLE_CONDITION';
15 DBIx::Class::Relationship::Base - Inter-table relationships
19 __PACKAGE__->add_relationship(
20 spiders => 'My::DB::Result::Creatures',
24 "$args->{foreign_alias}.id" => { -ident => "$args->{self_alias}.id" },
25 "$args->{foreign_alias}.type" => 'arachnid'
32 This class provides methods to describe the relationships between the
33 tables in your database model. These are the "bare bones" relationships
34 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
38 =head2 add_relationship
42 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
46 __PACKAGE__->add_relationship('rel_name',
50 Create a custom relationship between one result source and another
51 source, indicated by its class name.
55 The condition argument describes the C<ON> clause of the C<JOIN>
56 expression used to connect the two sources when creating SQL queries.
58 =head4 Simple equality
60 To create simple equality joins, supply a hashref containing the remote
61 table column name as the key(s) prefixed by C<'foreign.'>, and the
62 corresponding local table column name as the value(s) prefixed by C<'self.'>.
63 Both C<foreign> and C<self> are pseudo aliases and must be entered
64 literally. They will be replaced with the actual correct table alias
65 when the SQL is produced.
69 My::Schema::Author->has_many(
70 books => 'My::Schema::Book',
71 { 'foreign.author_id' => 'self.id' }
76 $author_rs->search_related('books')->next
78 will result in the following C<JOIN> clause:
80 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
82 This describes a relationship between the C<Author> table and the
83 C<Book> table where the C<Book> table has a column C<author_id>
84 containing the ID value of the C<Author>.
88 My::Schema::Book->has_many(
89 editions => 'My::Schema::Edition',
91 'foreign.publisher_id' => 'self.publisher_id',
92 'foreign.type_id' => 'self.type_id',
98 $book_rs->search_related('editions')->next
100 will result in the C<JOIN> clause:
103 LEFT JOIN edition editions ON
104 editions.publisher_id = me.publisher_id
105 AND editions.type_id = me.type_id ...
107 This describes the relationship from C<Book> to C<Edition>, where the
108 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
110 =head4 Multiple groups of simple equality conditions
112 As is the default in L<SQL::Abstract>, the key-value pairs will be
113 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
114 an arrayref. For example a condition like:
116 My::Schema::Item->has_many(
117 related_item_links => My::Schema::Item::Links,
119 { 'foreign.left_itemid' => 'self.id' },
120 { 'foreign.right_itemid' => 'self.id' },
124 will translate to the following C<JOIN> clause:
126 ... FROM item me JOIN item_relations related_item_links ON
127 related_item_links.left_itemid = me.id
128 OR related_item_links.right_itemid = me.id ...
130 This describes the relationship from C<Item> to C<Item::Links>, where
131 C<Item::Links> is a many-to-many linking table, linking items back to
132 themselves in a peer fashion (without a "parent-child" designation)
134 =head4 Custom join conditions
136 NOTE: The custom join condition specification mechanism is capable of
137 generating JOIN clauses of virtually unlimited complexity. This may limit
138 your ability to traverse some of the more involved relationship chains the
139 way you expect, *and* may bring your RDBMS to its knees. Exercise care
140 when declaring relationships as described here.
142 To specify joins which describe more than a simple equality of column
143 values, the custom join condition coderef syntax can be used. For
146 My::Schema::Artist->has_many(
147 cds_80s => 'My::Schema::CD',
152 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
153 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
160 $artist_rs->search_related('cds_80s')->next;
162 will result in the C<JOIN> clause:
164 ... FROM artist me LEFT JOIN cd cds_80s ON
165 cds_80s.artist = me.artistid
169 with the bind values:
173 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
174 same values that would be otherwise substituted for C<foreign> and C<self>
175 in the simple hashref syntax case.
177 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
178 like what one would supply as the first argument to
179 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
180 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
181 clause of the C<JOIN> statement associated with this relationship.
183 While every coderef-based condition must return a valid C<ON> clause, it may
184 elect to additionally return a simplified join-free condition hashref when
185 invoked as C<< $result->relationship >>, as opposed to
186 C<< $rs->related_resultset('relationship') >>. In this case C<$result> is
187 passed to the coderef as C<< $args->{self_resultobj} >>, so a user can do the
195 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
196 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
198 $args->{self_resultobj} && {
199 "$args->{foreign_alias}.artist" => $args->{self_resultobj}->artistid,
200 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
207 my $artist = $schema->resultset("Artist")->find({ id => 4 });
208 $artist->cds_80s->all;
210 Can skip a C<JOIN> altogether and instead produce:
212 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
214 WHERE cds_80s.artist = ?
218 With the bind values:
222 Note that in order to be able to use
223 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>,
224 the coderef must not only return as its second such a "simple" condition
225 hashref which does not depend on joins being available, but the hashref must
226 contain only plain values/deflatable objects, such that the result can be
227 passed directly to L<DBIx::Class::Relationship::Base/set_from_related>. For
228 instance the C<year> constraint in the above example prevents the relationship
229 from being used to create related objects (an exception will be thrown).
231 In order to allow the user to go truly crazy when generating a custom C<ON>
232 clause, the C<$args> hashref passed to the subroutine contains some extra
233 metadata. Currently the supplied coderef is executed as:
235 $relationship_info->{cond}->({
236 self_resultsource => The resultsource instance on which rel_name is registered
237 rel_name => The relationship name (does *NOT* always match foreign_alias)
239 self_alias => The alias of the invoking resultset
240 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
242 # only one of these (or none at all) will ever be supplied to aid in the
243 # construction of a join-free condition
244 self_resultobj => The invocant object itself in case of a $resultobj->$rel_name() call
245 foreign_resultobj => The related object in case of $resultobj->set_from_related($rel_name, $foreign_resultobj)
247 # deprecated inconsistent names, will be forever available for legacy code
248 self_rowobj => Old deprecated slot for self_resultobj
249 foreign_relname => Old deprecated slot for rel_name
254 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
255 be used as relationship attributes. In particular, the 'where' attribute is
256 useful for filtering relationships:
258 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
259 { 'foreign.user_id' => 'self.user_id' },
260 { where => { valid => 1 } }
263 The following attributes are also valid:
269 Explicitly specifies the type of join to use in the relationship. Any SQL
270 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
271 command immediately before C<JOIN>.
273 =item proxy =E<gt> $column | \@columns | \%column
275 The 'proxy' attribute can be used to retrieve values, and to perform
276 updates if the relationship has 'cascade_update' set. The 'might_have'
277 and 'has_one' relationships have this set by default; if you want a proxy
278 to update across a 'belongs_to' relationship, you must set the attribute
285 An arrayref containing a list of accessors in the foreign class to create in
286 the main class. If, for example, you do the following:
288 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
290 proxy => [ qw/notes/ ],
293 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
295 my $cd = MyApp::Schema::CD->find(1);
296 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
297 # created if it doesn't exist
299 For a 'belongs_to relationship, note the 'cascade_update':
301 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
302 { proxy => ['title'], cascade_update => 1 }
304 $track->title('New Title');
305 $track->update; # updates title in CD
309 A hashref where each key is the accessor you want installed in the main class,
310 and its value is the name of the original in the foreign class.
312 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
313 proxy => { cd_title => 'title' },
316 This will create an accessor named C<cd_title> on the C<$track> result object.
320 NOTE: you can pass a nested struct too, for example:
322 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
323 proxy => [ 'year', { cd_title => 'title' } ],
328 Specifies the type of accessor that should be created for the relationship.
329 Valid values are C<single> (for when there is only a single related object),
330 C<multi> (when there can be many), and C<filter> (for when there is a single
331 related object, but you also want the relationship accessor to double as
332 a column accessor). For C<multi> accessors, an add_to_* method is also
333 created, which calls C<create_related> for the relationship.
335 =item is_foreign_key_constraint
337 If you are using L<SQL::Translator> to create SQL for you and you find that it
338 is creating constraints where it shouldn't, or not creating them where it
339 should, set this attribute to a true or false value to override the detection
340 of when to create constraints.
344 If C<cascade_copy> is true on a C<has_many> relationship for an
345 object, then when you copy the object all the related objects will
346 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
347 in the C<$attr> hashref.
349 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
354 By default, DBIx::Class cascades deletes across C<has_many>,
355 C<has_one> and C<might_have> relationships. You can disable this
356 behaviour on a per-relationship basis by supplying
357 C<< cascade_delete => 0 >> in the relationship attributes.
359 The cascaded operations are performed after the requested delete,
360 so if your database has a constraint on the relationship, it will
361 have deleted/updated the related records or raised an exception
362 before DBIx::Class gets to perform the cascaded operation.
366 By default, DBIx::Class cascades updates across C<has_one> and
367 C<might_have> relationships. You can disable this behaviour on a
368 per-relationship basis by supplying C<< cascade_update => 0 >> in
369 the relationship attributes.
371 The C<belongs_to> relationship does not update across relationships
372 by default, so if you have a 'proxy' attribute on a belongs_to and want to
373 use 'update' on it, you muse set C<< cascade_update => 1 >>.
375 This is not a RDMS style cascade update - it purely means that when
376 an object has update called on it, all the related objects also
377 have update called. It will not change foreign keys automatically -
378 you must arrange to do this yourself.
380 =item on_delete / on_update
382 If you are using L<SQL::Translator> to create SQL for you, you can use these
383 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
384 type. If not supplied the SQLT parser will attempt to infer the constraint type by
385 interrogating the attributes of the B<opposite> relationship. For any 'multi'
386 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
387 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
388 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
389 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
390 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
391 C<< on_delete => '' >>, and the same for C<on_update> respectively.
395 Tells L<SQL::Translator> that the foreign key constraint it creates should be
396 deferrable. In other words, the user may request that the constraint be ignored
397 until the end of the transaction. Currently, only the PostgreSQL producer
398 actually supports this.
402 Tells L<SQL::Translator> to add an index for this constraint. Can also be
403 specified globally in the args to L<DBIx::Class::Schema/deploy> or
404 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
408 =head2 register_relationship
412 =item Arguments: $rel_name, $rel_info
416 Registers a relationship on the class. This is called internally by
417 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
421 sub register_relationship { }
423 =head2 related_resultset
427 =item Arguments: $rel_name
429 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
433 $rs = $cd->related_resultset('artist');
435 Returns a L<DBIx::Class::ResultSet> for the relationship named
438 =head2 $relationship_accessor
442 =item Arguments: none
444 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
448 # These pairs do the same thing
449 $result = $cd->related_resultset('artist')->single; # has_one relationship
450 $result = $cd->artist;
451 $rs = $cd->related_resultset('tracks'); # has_many relationship
454 This is the recommended way to traverse through relationships, based
455 on the L</accessor> name given in the relationship definition.
457 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
458 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
459 C<single> (returns only one row) or C<multi> (returns many rows). The
460 method may also return C<undef> if the relationship doesn't exist for
461 this instance (like in the case of C<might_have> relationships).
465 sub related_resultset {
468 $self->throw_exception("Can't call *_related as class methods")
473 return $self->{related_resultsets}{$rel}
474 if defined $self->{related_resultsets}{$rel};
476 return $self->{related_resultsets}{$rel} = do {
478 my $rel_info = $self->relationship_info($rel)
479 or $self->throw_exception( "No such relationship '$rel'" );
481 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
482 $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
484 $self->throw_exception( "Invalid query: @_" )
485 if (@_ > 1 && (@_ % 2 == 1));
486 my $query = ((@_ > 1) ? {@_} : shift);
488 my $rsrc = $self->result_source;
490 # condition resolution may fail if an incomplete master-object prefetch
491 # is encountered - that is ok during prefetch construction (not yet in_storage)
492 my ($cond, $is_crosstable) = try {
493 $rsrc->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel )
496 $self->throw_exception ($_) if $self->in_storage;
497 UNRESOLVABLE_CONDITION; # RV, no return()
500 # keep in mind that the following if() block is part of a do{} - no return()s!!!
501 if ($is_crosstable and ref $rel_info->{cond} eq 'CODE') {
503 # A WHOREIFFIC hack to reinvoke the entire condition resolution
504 # with the correct alias. Another way of doing this involves a
505 # lot of state passing around, and the @_ positions are already
506 # mapped out, making this crap a less icky option.
508 # The point of this exercise is to retain the spirit of the original
509 # $obj->search_related($rel) where the resulting rset will have the
510 # root alias as 'me', instead of $rel (as opposed to invoking
511 # $rs->search_related)
513 local $rsrc->{_relationships}{me} = $rsrc->{_relationships}{$rel}; # make the fake 'me' rel
514 my $obj_table_alias = lc($rsrc->source_name) . '__row';
515 $obj_table_alias =~ s/\W+/_/g;
517 $rsrc->resultset->search(
518 $self->ident_condition($obj_table_alias),
519 { alias => $obj_table_alias },
520 )->search_related('me', $query, $attrs)
523 # FIXME - this conditional doesn't seem correct - got to figure out
524 # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
525 # business seems shady - we could simply not query *at all*
526 if ($cond eq UNRESOLVABLE_CONDITION) {
527 my $reverse = $rsrc->reverse_relationship_info($rel);
528 foreach my $rev_rel (keys %$reverse) {
529 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
530 weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
532 weaken($attrs->{related_objects}{$rev_rel} = $self);
536 elsif (ref $cond eq 'ARRAY') {
538 if (ref $_ eq 'HASH') {
540 foreach my $key (keys %$_) {
541 my $newkey = $key !~ /\./ ? "me.$key" : $key;
542 $hash->{$newkey} = $_->{$key};
550 elsif (ref $cond eq 'HASH') {
551 foreach my $key (grep { ! /\./ } keys %$cond) {
552 $cond->{"me.$key"} = delete $cond->{$key};
556 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
557 $rsrc->related_source($rel)->resultset->search(
564 =head2 search_related
568 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
570 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
574 Run a search on a related resultset. The search will be restricted to the
575 results represented by the L<DBIx::Class::ResultSet> it was called
578 See L<DBIx::Class::ResultSet/search_related> for more information.
583 return shift->related_resultset(shift)->search(@_);
586 =head2 search_related_rs
588 This method works exactly the same as search_related, except that
589 it guarantees a resultset, even in list context.
593 sub search_related_rs {
594 return shift->related_resultset(shift)->search_rs(@_);
601 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
603 =item Return Value: $count
607 Returns the count of all the rows in the related resultset, restricted by the
608 current result or where conditions.
613 shift->search_related(@_)->count;
620 =item Arguments: $rel_name, \%col_data
622 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
626 Create a new result object of the related foreign class. It will magically set
627 any foreign key columns of the new object to the related primary key columns
628 of the source object for you. The newly created result will not be saved into
629 your storage until you call L<DBIx::Class::Row/insert> on it.
634 my ($self, $rel, $values) = @_;
636 # FIXME - this is a bad position for this (also an identical copy in
637 # set_from_related), but I have no saner way to hook, and I absolutely
638 # want this to throw at least for coderefs, instead of the "insert a NULL
639 # when it gets hard" insanity --ribasushi
641 # sanity check - currently throw when a complex coderef rel is encountered
642 # FIXME - should THROW MOAR!
644 if (ref $self) { # cdbi calls this as a class method, /me vomits
646 my $rsrc = $self->result_source;
647 my $rel_info = $rsrc->relationship_info($rel)
648 or $self->throw_exception( "No such relationship '$rel'" );
649 my (undef, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
650 $rel_info->{cond}, $rel, $self, $rel
653 $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
657 $nonequality_foreign_columns
659 my @unspecified_rel_condition_chunks = grep { ! exists $values->{$_} } @$nonequality_foreign_columns
661 $self->throw_exception(sprintf (
662 "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
664 map { "'$_'" } @unspecified_rel_condition_chunks
669 return $self->search_related($rel)->new_result($values);
672 =head2 create_related
676 =item Arguments: $rel_name, \%col_data
678 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
682 my $result = $obj->create_related($rel_name, \%col_data);
684 Creates a new result object, similarly to new_related, and also inserts the
685 result's data into your storage medium. See the distinction between C<create>
686 and C<new> in L<DBIx::Class::ResultSet> for details.
693 my $obj = $self->new_related($rel, @_)->insert;
694 delete $self->{related_resultsets}->{$rel};
702 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
704 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
708 my $result = $obj->find_related($rel_name, \%col_data);
710 Attempt to find a related object using its primary key or unique constraints.
711 See L<DBIx::Class::ResultSet/find> for details.
716 #my ($self, $rel, @args) = @_;
717 return shift->search_related(shift)->find(@_);
720 =head2 find_or_new_related
724 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
726 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
730 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
735 sub find_or_new_related {
737 my $obj = $self->find_related(@_);
738 return defined $obj ? $obj : $self->new_related(@_);
741 =head2 find_or_create_related
745 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
747 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
751 Find or create a result object of a related class. See
752 L<DBIx::Class::ResultSet/find_or_create> for details.
756 sub find_or_create_related {
758 my $obj = $self->find_related(@_);
759 return (defined($obj) ? $obj : $self->create_related(@_));
762 =head2 update_or_create_related
766 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
768 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
772 Update or create a result object of a related class. See
773 L<DBIx::Class::ResultSet/update_or_create> for details.
777 sub update_or_create_related {
778 #my ($self, $rel, @args) = @_;
779 shift->related_resultset(shift)->update_or_create(@_);
782 =head2 set_from_related
786 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
788 =item Return Value: not defined
792 $book->set_from_related('author', $author_obj);
793 $book->author($author_obj); ## same thing
795 Set column values on the current object, using related values from the given
796 related object. This is used to associate previously separate objects, for
797 example, to set the correct author for a book, find the Author object, then
798 call set_from_related on the book.
800 This is called internally when you pass existing objects as values to
801 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
803 The columns are only set in the local copy of the object, call L</update> to
804 set them in the storage.
808 sub set_from_related {
809 my ($self, $rel, $f_obj) = @_;
811 my $rsrc = $self->result_source;
812 my $rel_info = $rsrc->relationship_info($rel)
813 or $self->throw_exception( "No such relationship '$rel'" );
815 if (defined $f_obj) {
816 my $f_class = $rel_info->{class};
817 $self->throw_exception( "Object '$f_obj' isn't a ".$f_class )
818 unless blessed $f_obj and $f_obj->isa($f_class);
822 # FIXME - this is a bad position for this (also an identical copy in
823 # new_related), but I have no saner way to hook, and I absolutely
824 # want this to throw at least for coderefs, instead of the "insert a NULL
825 # when it gets hard" insanity --ribasushi
827 # sanity check - currently throw when a complex coderef rel is encountered
828 # FIXME - should THROW MOAR!
829 my ($cond, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
830 $rel_info->{cond}, $f_obj, $rel, $rel
832 $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
835 $self->throw_exception(sprintf (
836 "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
838 map { "'$_'" } @$nonequality_foreign_columns
839 )) if $nonequality_foreign_columns;
841 $self->set_columns($cond);
846 =head2 update_from_related
850 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
852 =item Return Value: not defined
856 $book->update_from_related('author', $author_obj);
858 The same as L</"set_from_related">, but the changes are immediately updated
863 sub update_from_related {
865 $self->set_from_related(@_);
869 =head2 delete_related
873 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
875 =item Return Value: $underlying_storage_rv
879 Delete any related row, subject to the given conditions. Internally, this
882 $self->search_related(@_)->delete
884 And returns the result of that.
890 my $obj = $self->search_related(@_)->delete;
891 delete $self->{related_resultsets}->{$_[0]};
897 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
900 =head3 has_many / multi
904 =item Arguments: \%col_data
906 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
910 Creates/inserts a new result object. Internally, this calls:
912 $self->create_related($rel, @_)
914 And returns the result of that.
920 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
922 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
926 my $role = $schema->resultset('Role')->find(1);
927 $actor->add_to_roles($role);
928 # creates a My::DBIC::Schema::ActorRoles linking table result object
930 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
931 # creates a new My::DBIC::Schema::Role result object and the linking table
932 # object with an extra column in the link
934 Adds a linking table object. If the first argument is a hash reference, the
935 related object is created first with the column values in the hash. If an object
936 reference is given, just the linking table object is created. In either case,
937 any additional column values for the linking table object can be specified in
940 See L<DBIx::Class::Relationship/many_to_many> for additional details.
944 B<Currently only available for C<many_to_many> relationships.>
948 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
950 =item Return Value: not defined
954 my $actor = $schema->resultset('Actor')->find(1);
955 my @roles = $schema->resultset('Role')->search({ role =>
956 { '-in' => ['Fred', 'Barney'] } } );
958 $actor->set_roles(\@roles);
959 # Replaces all of $actor's previous roles with the two named
961 $actor->set_roles(\@roles, { salary => 15_000_000 });
962 # Sets a column in the link table for all roles
965 Replace all the related objects with the given reference to a list of
966 objects. This does a C<delete> B<on the link table resultset> to remove the
967 association between the current object and all related objects, then calls
968 C<add_to_$rel> repeatedly to link all the new objects.
970 Note that this means that this method will B<not> delete any objects in the
971 table on the right side of the relation, merely that it will delete the link
974 Due to a mistake in the original implementation of this method, it will also
975 accept a list of objects or hash references. This is B<deprecated> and will be
976 removed in a future version.
978 =head2 remove_from_$rel
980 B<Currently only available for C<many_to_many> relationships.>
984 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
986 =item Return Value: not defined
990 my $role = $schema->resultset('Role')->find(1);
991 $actor->remove_from_roles($role);
992 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
994 Removes the link between the current object and the related object. Note that
995 the related object itself won't be deleted unless you call ->delete() on
996 it. This method just removes the link between the two objects.
998 =head1 AUTHOR AND CONTRIBUTORS
1000 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
1004 You may distribute this code under the same terms as Perl itself.