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 B<optional> join-free condition
185 consisting of a hashref with B<all keys being fully qualified names of columns
186 declared on the corresponding result source>. This boils down to two scenarios:
192 When relationship resolution is invoked after C<< $result->$rel_name >>, as
193 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
194 is passed to the coderef as C<< $args->{self_result_object} >>.
198 Alternatively when the user-space invokes resolution via
199 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
200 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
201 B<always> in the form of a hashref. If a foreign result object is supplied
202 (which is valid usage of L</set_from_related>), its values will be extracted
203 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
207 Note that the above scenarios are mutually exclusive, that is you will be supplied
208 none or only one of C<self_result_object> and C<foreign_values>. In other words if
209 you define your condition coderef as:
216 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
217 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
219 ! $args->{self_result_object} ? () : {
220 "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
221 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
223 ! $args->{foreign_values} ? () : {
224 "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
231 my $artist = $schema->resultset("Artist")->find({ id => 4 });
232 $artist->cds_80s->all;
234 Can skip a C<JOIN> altogether and instead produce:
236 SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
238 WHERE cds_80s.artist = ?
242 With the bind values:
248 my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
249 my $artist = $schema->resultset("Artist")->new({});
250 $artist->set_from_related('cds_80s');
252 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
254 Note that in order to be able to use L</set_from_related> (and by extension
255 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
256 the returned join free condition B<must> contain only plain values/deflatable
257 objects. For instance the C<year> constraint in the above example prevents
258 the relationship from being used to create related objects using
259 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
260 exception will be thrown).
262 In order to allow the user to go truly crazy when generating a custom C<ON>
263 clause, the C<$args> hashref passed to the subroutine contains some extra
264 metadata. Currently the supplied coderef is executed as:
266 $relationship_info->{cond}->({
267 self_resultsource => The resultsource instance on which rel_name is registered
268 rel_name => The relationship name (does *NOT* always match foreign_alias)
270 self_alias => The alias of the invoking resultset
271 foreign_alias => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
273 # only one of these (or none at all) will ever be supplied to aid in the
274 # construction of a join-free condition
276 self_result_object => The invocant *object* itself in case of a call like
277 $result_object->$rel_name( ... )
279 foreign_values => A *hashref* of related data: may be passed in directly or
280 derived via ->get_columns() from a related object in case of
281 $result_object->set_from_related( $rel_name, $foreign_result_object )
283 # deprecated inconsistent names, will be forever available for legacy code
284 self_rowobj => Old deprecated slot for self_result_object
285 foreign_relname => Old deprecated slot for rel_name
290 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
291 be used as relationship attributes. In particular, the 'where' attribute is
292 useful for filtering relationships:
294 __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
295 { 'foreign.user_id' => 'self.user_id' },
296 { where => { valid => 1 } }
299 The following attributes are also valid:
305 Explicitly specifies the type of join to use in the relationship. Any SQL
306 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
307 command immediately before C<JOIN>.
309 =item proxy =E<gt> $column | \@columns | \%column
311 The 'proxy' attribute can be used to retrieve values, and to perform
312 updates if the relationship has 'cascade_update' set. The 'might_have'
313 and 'has_one' relationships have this set by default; if you want a proxy
314 to update across a 'belongs_to' relationship, you must set the attribute
321 An arrayref containing a list of accessors in the foreign class to create in
322 the main class. If, for example, you do the following:
324 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
326 proxy => [ qw/notes/ ],
329 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
331 my $cd = MyApp::Schema::CD->find(1);
332 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
333 # created if it doesn't exist
335 For a 'belongs_to relationship, note the 'cascade_update':
337 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
338 { proxy => ['title'], cascade_update => 1 }
340 $track->title('New Title');
341 $track->update; # updates title in CD
345 A hashref where each key is the accessor you want installed in the main class,
346 and its value is the name of the original in the foreign class.
348 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
349 proxy => { cd_title => 'title' },
352 This will create an accessor named C<cd_title> on the C<$track> result object.
356 NOTE: you can pass a nested struct too, for example:
358 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
359 proxy => [ 'year', { cd_title => 'title' } ],
364 Specifies the type of accessor that should be created for the relationship.
365 Valid values are C<single> (for when there is only a single related object),
366 C<multi> (when there can be many), and C<filter> (for when there is a single
367 related object, but you also want the relationship accessor to double as
368 a column accessor). For C<multi> accessors, an add_to_* method is also
369 created, which calls C<create_related> for the relationship.
371 =item is_foreign_key_constraint
373 If you are using L<SQL::Translator> to create SQL for you and you find that it
374 is creating constraints where it shouldn't, or not creating them where it
375 should, set this attribute to a true or false value to override the detection
376 of when to create constraints.
380 If C<cascade_copy> is true on a C<has_many> relationship for an
381 object, then when you copy the object all the related objects will
382 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
383 in the C<$attr> hashref.
385 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
390 By default, DBIx::Class cascades deletes across C<has_many>,
391 C<has_one> and C<might_have> relationships. You can disable this
392 behaviour on a per-relationship basis by supplying
393 C<< cascade_delete => 0 >> in the relationship attributes.
395 The cascaded operations are performed after the requested delete,
396 so if your database has a constraint on the relationship, it will
397 have deleted/updated the related records or raised an exception
398 before DBIx::Class gets to perform the cascaded operation.
402 By default, DBIx::Class cascades updates across C<has_one> and
403 C<might_have> relationships. You can disable this behaviour on a
404 per-relationship basis by supplying C<< cascade_update => 0 >> in
405 the relationship attributes.
407 The C<belongs_to> relationship does not update across relationships
408 by default, so if you have a 'proxy' attribute on a belongs_to and want to
409 use 'update' on it, you must set C<< cascade_update => 1 >>.
411 This is not a RDMS style cascade update - it purely means that when
412 an object has update called on it, all the related objects also
413 have update called. It will not change foreign keys automatically -
414 you must arrange to do this yourself.
416 =item on_delete / on_update
418 If you are using L<SQL::Translator> to create SQL for you, you can use these
419 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
420 type. If not supplied the SQLT parser will attempt to infer the constraint type by
421 interrogating the attributes of the B<opposite> relationship. For any 'multi'
422 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
423 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
424 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
425 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
426 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
427 C<< on_delete => '' >>, and the same for C<on_update> respectively.
431 Tells L<SQL::Translator> that the foreign key constraint it creates should be
432 deferrable. In other words, the user may request that the constraint be ignored
433 until the end of the transaction. Currently, only the PostgreSQL producer
434 actually supports this.
438 Tells L<SQL::Translator> to add an index for this constraint. Can also be
439 specified globally in the args to L<DBIx::Class::Schema/deploy> or
440 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
444 =head2 register_relationship
448 =item Arguments: $rel_name, $rel_info
452 Registers a relationship on the class. This is called internally by
453 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
457 sub register_relationship { }
459 =head2 related_resultset
463 =item Arguments: $rel_name
465 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
469 $rs = $cd->related_resultset('artist');
471 Returns a L<DBIx::Class::ResultSet> for the relationship named
474 =head2 $relationship_accessor
478 =item Arguments: none
480 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
484 # These pairs do the same thing
485 $result = $cd->related_resultset('artist')->single; # has_one relationship
486 $result = $cd->artist;
487 $rs = $cd->related_resultset('tracks'); # has_many relationship
490 This is the recommended way to traverse through relationships, based
491 on the L</accessor> name given in the relationship definition.
493 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
494 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
495 C<single> (returns only one row) or C<multi> (returns many rows). The
496 method may also return C<undef> if the relationship doesn't exist for
497 this instance (like in the case of C<might_have> relationships).
501 sub related_resultset {
504 $self->throw_exception("Can't call *_related as class methods")
509 return $self->{related_resultsets}{$rel}
510 if defined $self->{related_resultsets}{$rel};
512 return $self->{related_resultsets}{$rel} = do {
514 my $rsrc = $self->result_source;
516 my $rel_info = $rsrc->relationship_info($rel)
517 or $self->throw_exception( "No such relationship '$rel'" );
519 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
520 $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
522 $self->throw_exception( "Invalid query: @_" )
523 if (@_ > 1 && (@_ % 2 == 1));
524 my $query = ((@_ > 1) ? {@_} : shift);
526 my ($cond, $is_crosstable) = $rsrc->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel );
528 # keep in mind that the following if() block is part of a do{} - no return()s!!!
529 if ($is_crosstable and ref $rel_info->{cond} eq 'CODE') {
531 # A WHOREIFFIC hack to reinvoke the entire condition resolution
532 # with the correct alias. Another way of doing this involves a
533 # lot of state passing around, and the @_ positions are already
534 # mapped out, making this crap a less icky option.
536 # The point of this exercise is to retain the spirit of the original
537 # $obj->search_related($rel) where the resulting rset will have the
538 # root alias as 'me', instead of $rel (as opposed to invoking
539 # $rs->search_related)
541 # make the fake 'me' rel
542 local $rsrc->{_relationships}{me} = {
543 %{ $rsrc->{_relationships}{$rel} },
544 _original_name => $rel,
547 my $obj_table_alias = lc($rsrc->source_name) . '__row';
548 $obj_table_alias =~ s/\W+/_/g;
550 $rsrc->resultset->search(
551 $self->ident_condition($obj_table_alias),
552 { alias => $obj_table_alias },
553 )->search_related('me', $query, $attrs)
556 # FIXME - this conditional doesn't seem correct - got to figure out
557 # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
558 # business seems shady - we could simply not query *at all*
559 if ($cond eq UNRESOLVABLE_CONDITION) {
560 my $reverse = $rsrc->reverse_relationship_info($rel);
561 foreach my $rev_rel (keys %$reverse) {
562 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
563 weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
565 weaken($attrs->{related_objects}{$rev_rel} = $self);
569 elsif (ref $cond eq 'ARRAY') {
571 if (ref $_ eq 'HASH') {
573 foreach my $key (keys %$_) {
574 my $newkey = $key !~ /\./ ? "me.$key" : $key;
575 $hash->{$newkey} = $_->{$key};
583 elsif (ref $cond eq 'HASH') {
584 foreach my $key (grep { ! /\./ } keys %$cond) {
585 $cond->{"me.$key"} = delete $cond->{$key};
589 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
590 $rsrc->related_source($rel)->resultset->search(
597 =head2 search_related
601 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
603 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
607 Run a search on a related resultset. The search will be restricted to the
608 results represented by the L<DBIx::Class::ResultSet> it was called
611 See L<DBIx::Class::ResultSet/search_related> for more information.
616 return shift->related_resultset(shift)->search(@_);
619 =head2 search_related_rs
621 This method works exactly the same as search_related, except that
622 it guarantees a resultset, even in list context.
626 sub search_related_rs {
627 return 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.
646 shift->search_related(@_)->count;
653 =item Arguments: $rel_name, \%col_data
655 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
659 Create a new result object of the related foreign class. It will magically set
660 any foreign key columns of the new object to the related primary key columns
661 of the source object for you. The newly created result will not be saved into
662 your storage until you call L<DBIx::Class::Row/insert> on it.
667 my ($self, $rel, $data) = @_;
669 return $self->search_related($rel)->new_result( $self->result_source->_resolve_relationship_condition (
670 infer_values_based_on => $data,
672 self_result_object => $self,
673 foreign_alias => $rel,
675 )->{inferred_values} );
678 =head2 create_related
682 =item Arguments: $rel_name, \%col_data
684 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
688 my $result = $obj->create_related($rel_name, \%col_data);
690 Creates a new result object, similarly to new_related, and also inserts the
691 result's data into your storage medium. See the distinction between C<create>
692 and C<new> in L<DBIx::Class::ResultSet> for details.
699 my $obj = $self->new_related($rel, @_)->insert;
700 delete $self->{related_resultsets}->{$rel};
708 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
710 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
714 my $result = $obj->find_related($rel_name, \%col_data);
716 Attempt to find a related object using its primary key or unique constraints.
717 See L<DBIx::Class::ResultSet/find> for details.
722 #my ($self, $rel, @args) = @_;
723 return shift->search_related(shift)->find(@_);
726 =head2 find_or_new_related
730 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
732 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
736 Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
741 sub find_or_new_related {
743 my $obj = $self->find_related(@_);
744 return defined $obj ? $obj : $self->new_related(@_);
747 =head2 find_or_create_related
751 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
753 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
757 Find or create a result object of a related class. See
758 L<DBIx::Class::ResultSet/find_or_create> for details.
762 sub find_or_create_related {
764 my $obj = $self->find_related(@_);
765 return (defined($obj) ? $obj : $self->create_related(@_));
768 =head2 update_or_create_related
772 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
774 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
778 Update or create a result object of a related class. See
779 L<DBIx::Class::ResultSet/update_or_create> for details.
783 sub update_or_create_related {
784 #my ($self, $rel, @args) = @_;
785 shift->related_resultset(shift)->update_or_create(@_);
788 =head2 set_from_related
792 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
794 =item Return Value: not defined
798 $book->set_from_related('author', $author_obj);
799 $book->author($author_obj); ## same thing
801 Set column values on the current object, using related values from the given
802 related object. This is used to associate previously separate objects, for
803 example, to set the correct author for a book, find the Author object, then
804 call set_from_related on the book.
806 This is called internally when you pass existing objects as values to
807 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
809 The columns are only set in the local copy of the object, call
810 L<update|DBIx::Class::Row/update> to update them in the storage.
814 sub set_from_related {
815 my ($self, $rel, $f_obj) = @_;
817 $self->set_columns( $self->result_source->_resolve_relationship_condition (
818 infer_values_based_on => {},
820 foreign_values => $f_obj,
821 foreign_alias => $rel,
823 )->{inferred_values} );
828 =head2 update_from_related
832 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
834 =item Return Value: not defined
838 $book->update_from_related('author', $author_obj);
840 The same as L</"set_from_related">, but the changes are immediately updated
845 sub update_from_related {
847 $self->set_from_related(@_);
851 =head2 delete_related
855 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
857 =item Return Value: $underlying_storage_rv
861 Delete any related row, subject to the given conditions. Internally, this
864 $self->search_related(@_)->delete
866 And returns the result of that.
872 my $obj = $self->search_related(@_)->delete;
873 delete $self->{related_resultsets}->{$_[0]};
879 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
882 =head3 has_many / multi
886 =item Arguments: \%col_data
888 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
892 Creates/inserts a new result object. Internally, this calls:
894 $self->create_related($rel, @_)
896 And returns the result of that.
902 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
904 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
908 my $role = $schema->resultset('Role')->find(1);
909 $actor->add_to_roles($role);
910 # creates a My::DBIC::Schema::ActorRoles linking table result object
912 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
913 # creates a new My::DBIC::Schema::Role result object and the linking table
914 # object with an extra column in the link
916 Adds a linking table object. If the first argument is a hash reference, the
917 related object is created first with the column values in the hash. If an object
918 reference is given, just the linking table object is created. In either case,
919 any additional column values for the linking table object can be specified in
922 See L<DBIx::Class::Relationship/many_to_many> for additional details.
926 B<Currently only available for C<many_to_many> relationships.>
930 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
932 =item Return Value: not defined
936 my $actor = $schema->resultset('Actor')->find(1);
937 my @roles = $schema->resultset('Role')->search({ role =>
938 { '-in' => ['Fred', 'Barney'] } } );
940 $actor->set_roles(\@roles);
941 # Replaces all of $actor's previous roles with the two named
943 $actor->set_roles(\@roles, { salary => 15_000_000 });
944 # Sets a column in the link table for all roles
947 Replace all the related objects with the given reference to a list of
948 objects. This does a C<delete> B<on the link table resultset> to remove the
949 association between the current object and all related objects, then calls
950 C<add_to_$rel> repeatedly to link all the new objects.
952 Note that this means that this method will B<not> delete any objects in the
953 table on the right side of the relation, merely that it will delete the link
956 Due to a mistake in the original implementation of this method, it will also
957 accept a list of objects or hash references. This is B<deprecated> and will be
958 removed in a future version.
960 =head2 remove_from_$rel
962 B<Currently only available for C<many_to_many> relationships.>
966 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
968 =item Return Value: not defined
972 my $role = $schema->resultset('Role')->find(1);
973 $actor->remove_from_roles($role);
974 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
976 Removes the link between the current object and the related object. Note that
977 the related object itself won't be deleted unless you call ->delete() on
978 it. This method just removes the link between the two objects.
980 =head1 FURTHER QUESTIONS?
982 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
984 =head1 COPYRIGHT AND LICENSE
986 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
987 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
988 redistribute it and/or modify it under the same terms as the
989 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.