8e4b280150954ee3d200170a7b01b79b4462aa5c
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Relationship / Base.pm
1 package DBIx::Class::Relationship::Base;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class/;
7
8 use Scalar::Util qw/weaken blessed/;
9 use DBIx::Class::_Util qw( UNRESOLVABLE_CONDITION fail_on_internal_call );
10 use namespace::clean;
11
12 =head1 NAME
13
14 DBIx::Class::Relationship::Base - Inter-table relationships
15
16 =head1 SYNOPSIS
17
18   __PACKAGE__->add_relationship(
19     spiders => 'My::DB::Result::Creatures',
20     sub {
21       my $args = shift;
22       return {
23         "$args->{foreign_alias}.id"   => { -ident => "$args->{self_alias}.id" },
24         "$args->{foreign_alias}.type" => 'arachnid'
25       };
26     },
27   );
28
29 =head1 DESCRIPTION
30
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>.
34
35 =head1 METHODS
36
37 =head2 add_relationship
38
39 =over 4
40
41 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
42
43 =back
44
45   __PACKAGE__->add_relationship('rel_name',
46                                 'Foreign::Class',
47                                 $condition, $attrs);
48
49 Create a custom relationship between one result source and another
50 source, indicated by its class name.
51
52 =head3 condition
53
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.
56
57 =head4 Simple equality
58
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.
65
66 For example given:
67
68   My::Schema::Author->has_many(
69     books => 'My::Schema::Book',
70     { 'foreign.author_id' => 'self.id' }
71   );
72
73 A query like:
74
75   $author_rs->search_related('books')->next
76
77 will result in the following C<JOIN> clause:
78
79   ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
80
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>.
84
85 Similarly:
86
87   My::Schema::Book->has_many(
88     editions => 'My::Schema::Edition',
89     {
90       'foreign.publisher_id' => 'self.publisher_id',
91       'foreign.type_id'      => 'self.type_id',
92     }
93   );
94
95   ...
96
97   $book_rs->search_related('editions')->next
98
99 will result in the C<JOIN> clause:
100
101   ... FROM book me
102       LEFT JOIN edition editions ON
103            editions.publisher_id = me.publisher_id
104        AND editions.type_id = me.type_id ...
105
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"):
108
109 =head4 Multiple groups of simple equality conditions
110
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:
114
115   My::Schema::Item->has_many(
116     related_item_links => My::Schema::Item::Links,
117     [
118       { 'foreign.left_itemid'  => 'self.id' },
119       { 'foreign.right_itemid' => 'self.id' },
120     ],
121   );
122
123 will translate to the following C<JOIN> clause:
124
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 ...
128
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)
132
133 =head4 Custom join conditions
134
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.
140
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
143 example:
144
145   My::Schema::Artist->has_many(
146     cds_80s => 'My::Schema::CD',
147     sub {
148       my $args = shift;
149
150       return {
151         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
152         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
153       };
154     }
155   );
156
157   ...
158
159   $artist_rs->search_related('cds_80s')->next;
160
161 will result in the C<JOIN> clause:
162
163   ... FROM artist me LEFT JOIN cd cds_80s ON
164         cds_80s.artist = me.artistid
165     AND cds_80s.year < ?
166     AND cds_80s.year > ?
167
168 with the bind values:
169
170    '1990', '1979'
171
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.
175
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.
181
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:
186
187 =over
188
189 =item *
190
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} >>.
194
195 =item *
196
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>.
203
204 =back
205
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:
209
210   sub {
211     my $args = shift;
212
213     return (
214       {
215         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
216         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
217       },
218       ! $args->{self_result_object} ? () : {
219         "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
220         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
221       },
222       ! $args->{foreign_values} ? () : {
223         "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
224       }
225     );
226   }
227
228 Then this code:
229
230     my $artist = $schema->resultset("Artist")->find({ id => 4 });
231     $artist->cds_80s->all;
232
233 Can skip a C<JOIN> altogether and instead produce:
234
235     SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
236       FROM cd cds_80s
237       WHERE cds_80s.artist = ?
238         AND cds_80s.year < ?
239         AND cds_80s.year > ?
240
241 With the bind values:
242
243     '4', '1990', '1979'
244
245 While this code:
246
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');
250
251 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
252
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).
260
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:
264
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)
268
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)
271
272     # only one of these (or none at all) will ever be supplied to aid in the
273     # construction of a join-free condition
274
275     self_result_object  => The invocant *object* itself in case of a call like
276                            $result_object->$rel_name( ... )
277
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 )
281
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
285   });
286
287 =head3 attributes
288
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:
292
293      __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
294         { 'foreign.user_id' => 'self.user_id' },
295         { where => { valid => 1 } }
296     );
297
298 The following attributes are also valid:
299
300 =over 4
301
302 =item join_type
303
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>.
307
308 =item proxy =E<gt> $column | \@columns | \%column
309
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
314 yourself.
315
316 =over 4
317
318 =item \@columns
319
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:
322
323   MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
324     undef, {
325       proxy => [ qw/notes/ ],
326     });
327
328 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
329
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
333
334 For a 'belongs_to relationship, note the 'cascade_update':
335
336   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
337       { proxy => ['title'], cascade_update => 1 }
338   );
339   $track->title('New Title');
340   $track->update; # updates title in CD
341
342 =item \%column
343
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.
346
347   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
348       proxy => { cd_title => 'title' },
349   });
350
351 This will create an accessor named C<cd_title> on the C<$track> result object.
352
353 =back
354
355 NOTE: you can pass a nested struct too, for example:
356
357   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
358     proxy => [ 'year', { cd_title => 'title' } ],
359   });
360
361 =item accessor
362
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.
369
370 =item is_foreign_key_constraint
371
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.
376
377 =item cascade_copy
378
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.
383
384 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
385 relationships.
386
387 =item cascade_delete
388
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.
393
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.
398
399 =item cascade_update
400
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.
405
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 >>.
409
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.
414
415 =item on_delete / on_update
416
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.
427
428 =item is_deferrable
429
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.
434
435 =item add_fk_index
436
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.
440
441 =back
442
443 =head2 register_relationship
444
445 =over 4
446
447 =item Arguments: $rel_name, $rel_info
448
449 =back
450
451 Registers a relationship on the class. This is called internally by
452 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
453
454 =cut
455
456 sub register_relationship { }
457
458 =head2 related_resultset
459
460 =over 4
461
462 =item Arguments: $rel_name
463
464 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
465
466 =back
467
468   $rs = $cd->related_resultset('artist');
469
470 Returns a L<DBIx::Class::ResultSet> for the relationship named
471 $rel_name.
472
473 =head2 $relationship_accessor
474
475 =over 4
476
477 =item Arguments: none
478
479 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
480
481 =back
482
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
487   $rs = $cd->tracks;
488
489 This is the recommended way to traverse through relationships, based
490 on the L</accessor> name given in the relationship definition.
491
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).
497
498 =cut
499
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)'
506   ) if @_ > 2;
507
508   $_[0]->throw_exception("Can't call *_related as class methods")
509     unless ref $_[0];
510
511   return $_[0]->{related_resultsets}{$_[1]}
512     if defined $_[0]->{related_resultsets}{$_[1]};
513
514   my ($self, $rel) = @_;
515
516   return $self->{related_resultsets}{$rel} = do {
517
518     my $rsrc = $self->result_source;
519
520     my $rel_info = $rsrc->relationship_info($rel)
521       or $self->throw_exception( "No such relationship '$rel'" );
522
523     my $cond_res = $rsrc->_resolve_relationship_condition(
524       rel_name => $rel,
525       self_result_object => $self,
526
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',
531
532       self_alias => "!!!\xFF()!!!_SHOULD_NEVER_BE_SEEN_IN_USE_!!!()\xFF!!!",
533
534       # not strictly necessary, but shouldn't hurt either
535       require_join_free_condition => !!(ref $rel_info->{cond} ne 'CODE'),
536     );
537
538     # keep in mind that the following if() block is part of a do{} - no return()s!!!
539     if (
540       ! $cond_res->{join_free_condition}
541         and
542       ref $rel_info->{cond} eq 'CODE'
543     ) {
544
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.
549       #
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)
554
555       # make the fake 'me' rel
556       local $rsrc->{_relationships}{me} = {
557         %{ $rsrc->{_relationships}{$rel} },
558         _original_name => $rel,
559       };
560
561       my $obj_table_alias = lc($rsrc->source_name) . '__row';
562       $obj_table_alias =~ s/\W+/_/g;
563
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})
568     }
569     else {
570
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*
574       my $attrs;
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);
581           } else {
582             weaken($attrs->{related_objects}{$rev_rel} = $self);
583           }
584         }
585       }
586
587       $rsrc->related_source($rel)->resultset->search(
588         $cond_res->{join_free_condition},
589         $attrs || $rel_info->{attrs},
590       );
591     }
592   };
593 }
594
595 =head2 search_related
596
597 =over 4
598
599 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
600
601 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
602
603 =back
604
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
607 upon.
608
609 See L<DBIx::Class::ResultSet/search_related> for more information.
610
611 =cut
612
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(@_);
616 }
617
618 =head2 search_related_rs
619
620 This method works exactly the same as search_related, except that
621 it guarantees a resultset, even in list context.
622
623 =cut
624
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(@_)
628 }
629
630 =head2 count_related
631
632 =over 4
633
634 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
635
636 =item Return Value: $count
637
638 =back
639
640 Returns the count of all the rows in the related resultset, restricted by the
641 current result or where conditions.
642
643 =cut
644
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;
648 }
649
650 =head2 new_related
651
652 =over 4
653
654 =item Arguments: $rel_name, \%col_data
655
656 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
657
658 =back
659
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.
664
665 =cut
666
667 sub new_related {
668   my ($self, $rel, $data) = @_;
669
670   $self->related_resultset($rel)->new_result( $self->result_source->_resolve_relationship_condition (
671     infer_values_based_on => $data,
672     rel_name => $rel,
673     self_result_object => $self,
674     foreign_alias => $rel,
675     self_alias => 'me',
676   )->{inferred_values} );
677 }
678
679 =head2 create_related
680
681 =over 4
682
683 =item Arguments: $rel_name, \%col_data
684
685 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
686
687 =back
688
689   my $result = $obj->create_related($rel_name, \%col_data);
690
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.
694
695 =cut
696
697 sub create_related {
698   my $self = shift;
699   my $rel = shift;
700   my $obj = $self->new_related($rel, @_)->insert;
701   delete $self->{related_resultsets}->{$rel};
702   return $obj;
703 }
704
705 =head2 find_related
706
707 =over 4
708
709 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
710
711 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
712
713 =back
714
715   my $result = $obj->find_related($rel_name, \%col_data);
716
717 Attempt to find a related object using its primary key or unique constraints.
718 See L<DBIx::Class::ResultSet/find> for details.
719
720 =cut
721
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(@_);
726 }
727
728 =head2 find_or_new_related
729
730 =over 4
731
732 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
733
734 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
735
736 =back
737
738 Find a result object of a related class.  See L<DBIx::Class::ResultSet/find_or_new>
739 for details.
740
741 =cut
742
743 sub find_or_new_related {
744   my $self = shift;
745   my $rel = shift;
746   my $obj = $self->related_resultset($rel)->find(@_);
747   return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
748 }
749
750 =head2 find_or_create_related
751
752 =over 4
753
754 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
755
756 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
757
758 =back
759
760 Find or create a result object of a related class. See
761 L<DBIx::Class::ResultSet/find_or_create> for details.
762
763 =cut
764
765 sub find_or_create_related {
766   my $self = shift;
767   my $rel = shift;
768   my $obj = $self->related_resultset($rel)->find(@_);
769   return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
770 }
771
772 =head2 update_or_create_related
773
774 =over 4
775
776 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
777
778 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
779
780 =back
781
782 Update or create a result object of a related class. See
783 L<DBIx::Class::ResultSet/update_or_create> for details.
784
785 =cut
786
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(@_);
791 }
792
793 =head2 set_from_related
794
795 =over 4
796
797 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
798
799 =item Return Value: not defined
800
801 =back
802
803   $book->set_from_related('author', $author_obj);
804   $book->author($author_obj);                      ## same thing
805
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.
810
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.
813
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.
816
817 =cut
818
819 sub set_from_related {
820   my ($self, $rel, $f_obj) = @_;
821
822   $self->set_columns( $self->result_source->_resolve_relationship_condition (
823     infer_values_based_on => {},
824     rel_name => $rel,
825     foreign_values => $f_obj,
826     foreign_alias => $rel,
827     self_alias => 'me',
828   )->{inferred_values} );
829
830   return 1;
831 }
832
833 =head2 update_from_related
834
835 =over 4
836
837 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
838
839 =item Return Value: not defined
840
841 =back
842
843   $book->update_from_related('author', $author_obj);
844
845 The same as L</"set_from_related">, but the changes are immediately updated
846 in storage.
847
848 =cut
849
850 sub update_from_related {
851   my $self = shift;
852   $self->set_from_related(@_);
853   $self->update;
854 }
855
856 =head2 delete_related
857
858 =over 4
859
860 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
861
862 =item Return Value: $underlying_storage_rv
863
864 =back
865
866 Delete any related row, subject to the given conditions.  Internally, this
867 calls:
868
869   $self->search_related(@_)->delete
870
871 And returns the result of that.
872
873 =cut
874
875 sub delete_related {
876   my $self = shift;
877   my $rel = shift;
878   my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
879   delete $self->{related_resultsets}->{$rel};
880   return $obj;
881 }
882
883 =head2 add_to_$rel
884
885 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
886 relationships.>
887
888 =head3 has_many / multi
889
890 =over 4
891
892 =item Arguments: \%col_data
893
894 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
895
896 =back
897
898 Creates/inserts a new result object.  Internally, this calls:
899
900   $self->create_related($rel, @_)
901
902 And returns the result of that.
903
904 =head3 many_to_many
905
906 =over 4
907
908 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
909
910 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
911
912 =back
913
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
917
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
921
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
926 C<\%link_col_data>.
927
928 See L<DBIx::Class::Relationship/many_to_many> for additional details.
929
930 =head2 set_$rel
931
932 B<Currently only available for C<many_to_many> relationships.>
933
934 =over 4
935
936 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
937
938 =item Return Value: not defined
939
940 =back
941
942   my $actor = $schema->resultset('Actor')->find(1);
943   my @roles = $schema->resultset('Role')->search({ role =>
944      { '-in' => ['Fred', 'Barney'] } } );
945
946   $actor->set_roles(\@roles);
947      # Replaces all of $actor's previous roles with the two named
948
949   $actor->set_roles(\@roles, { salary => 15_000_000 });
950      # Sets a column in the link table for all roles
951
952
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.
957
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
960 between them.
961
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.
965
966 =head2 remove_from_$rel
967
968 B<Currently only available for C<many_to_many> relationships.>
969
970 =over 4
971
972 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
973
974 =item Return Value: not defined
975
976 =back
977
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
981
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.
985
986 =head1 FURTHER QUESTIONS?
987
988 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
989
990 =head1 COPYRIGHT AND LICENSE
991
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>.
996
997 =cut
998
999 1;