Some cleanup of the resolve_relationship_condition callsites
[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(
10   UNRESOLVABLE_CONDITION DUMMY_ALIASPAIR
11   fail_on_internal_call
12 );
13 use DBIx::Class::Carp;
14 use namespace::clean;
15
16 =head1 NAME
17
18 DBIx::Class::Relationship::Base - Inter-table relationships
19
20 =head1 SYNOPSIS
21
22   __PACKAGE__->add_relationship(
23     spiders => 'My::DB::Result::Creatures',
24     sub {
25       my $args = shift;
26       return {
27         "$args->{foreign_alias}.id"   => { -ident => "$args->{self_alias}.id" },
28         "$args->{foreign_alias}.type" => 'arachnid'
29       };
30     },
31   );
32
33 =head1 DESCRIPTION
34
35 This class provides methods to describe the relationships between the
36 tables in your database model. These are the "bare bones" relationships
37 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
38
39 =head1 METHODS
40
41 =head2 add_relationship
42
43 =over 4
44
45 =item Arguments: $rel_name, $foreign_class, $condition, $attrs
46
47 =back
48
49   __PACKAGE__->add_relationship('rel_name',
50                                 'Foreign::Class',
51                                 $condition, $attrs);
52
53 Create a custom relationship between one result source and another
54 source, indicated by its class name.
55
56 =head3 condition
57
58 The condition argument describes the C<ON> clause of the C<JOIN>
59 expression used to connect the two sources when creating SQL queries.
60
61 =head4 Simple equality
62
63 To create simple equality joins, supply a hashref containing the remote
64 table column name as the key(s) prefixed by C<'foreign.'>, and the
65 corresponding local table column name as the value(s) prefixed by C<'self.'>.
66 Both C<foreign> and C<self> are pseudo aliases and must be entered
67 literally. They will be replaced with the actual correct table alias
68 when the SQL is produced.
69
70 For example given:
71
72   My::Schema::Author->has_many(
73     books => 'My::Schema::Book',
74     { 'foreign.author_id' => 'self.id' }
75   );
76
77 A query like:
78
79   $author_rs->search_related('books')->next
80
81 will result in the following C<JOIN> clause:
82
83   ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
84
85 This describes a relationship between the C<Author> table and the
86 C<Book> table where the C<Book> table has a column C<author_id>
87 containing the ID value of the C<Author>.
88
89 Similarly:
90
91   My::Schema::Book->has_many(
92     editions => 'My::Schema::Edition',
93     {
94       'foreign.publisher_id' => 'self.publisher_id',
95       'foreign.type_id'      => 'self.type_id',
96     }
97   );
98
99   ...
100
101   $book_rs->search_related('editions')->next
102
103 will result in the C<JOIN> clause:
104
105   ... FROM book me
106       LEFT JOIN edition editions ON
107            editions.publisher_id = me.publisher_id
108        AND editions.type_id = me.type_id ...
109
110 This describes the relationship from C<Book> to C<Edition>, where the
111 C<Edition> table refers to a publisher and a type (e.g. "paperback"):
112
113 =head4 Multiple groups of simple equality conditions
114
115 As is the default in L<SQL::Abstract>, the key-value pairs will be
116 C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
117 an arrayref. For example a condition like:
118
119   My::Schema::Item->has_many(
120     related_item_links => My::Schema::Item::Links,
121     [
122       { 'foreign.left_itemid'  => 'self.id' },
123       { 'foreign.right_itemid' => 'self.id' },
124     ],
125   );
126
127 will translate to the following C<JOIN> clause:
128
129  ... FROM item me JOIN item_relations related_item_links ON
130          related_item_links.left_itemid = me.id
131       OR related_item_links.right_itemid = me.id ...
132
133 This describes the relationship from C<Item> to C<Item::Links>, where
134 C<Item::Links> is a many-to-many linking table, linking items back to
135 themselves in a peer fashion (without a "parent-child" designation)
136
137 =head4 Custom join conditions
138
139   NOTE: The custom join condition specification mechanism is capable of
140   generating JOIN clauses of virtually unlimited complexity. This may limit
141   your ability to traverse some of the more involved relationship chains the
142   way you expect, *and* may bring your RDBMS to its knees. Exercise care
143   when declaring relationships as described here.
144
145 To specify joins which describe more than a simple equality of column
146 values, the custom join condition coderef syntax can be used. For
147 example:
148
149   My::Schema::Artist->has_many(
150     cds_80s => 'My::Schema::CD',
151     sub {
152       my $args = shift;
153
154       return {
155         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
156         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
157       };
158     }
159   );
160
161   ...
162
163   $artist_rs->search_related('cds_80s')->next;
164
165 will result in the C<JOIN> clause:
166
167   ... FROM artist me LEFT JOIN cd cds_80s ON
168         cds_80s.artist = me.artistid
169     AND cds_80s.year < ?
170     AND cds_80s.year > ?
171
172 with the bind values:
173
174    '1990', '1979'
175
176 C<< $args->{foreign_alias} >> and C<< $args->{self_alias} >> are supplied the
177 same values that would be otherwise substituted for C<foreign> and C<self>
178 in the simple hashref syntax case.
179
180 The coderef is expected to return a valid L<SQL::Abstract> query-structure, just
181 like what one would supply as the first argument to
182 L<DBIx::Class::ResultSet/search>. The return value will be passed directly to
183 L<SQL::Abstract> and the resulting SQL will be used verbatim as the C<ON>
184 clause of the C<JOIN> statement associated with this relationship.
185
186 While every coderef-based condition must return a valid C<ON> clause, it may
187 elect to additionally return a simplified B<optional> join-free condition
188 consisting of a hashref with B<all keys being fully qualified names of columns
189 declared on the corresponding result source>. This boils down to two scenarios:
190
191 =over
192
193 =item *
194
195 When relationship resolution is invoked after C<< $result->$rel_name >>, as
196 opposed to C<< $rs->related_resultset($rel_name) >>, the C<$result> object
197 is passed to the coderef as C<< $args->{self_result_object} >>.
198
199 =item *
200
201 Alternatively when the user-space invokes resolution via
202 C<< $result->set_from_related( $rel_name => $foreign_values_or_object ) >>, the
203 corresponding data is passed to the coderef as C<< $args->{foreign_values} >>,
204 B<always> in the form of a hashref. If a foreign result object is supplied
205 (which is valid usage of L</set_from_related>), its values will be extracted
206 into hashref form by calling L<get_columns|DBIx::Class::Row/get_columns>.
207
208 =back
209
210 Note that the above scenarios are mutually exclusive, that is you will be supplied
211 none or only one of C<self_result_object> and C<foreign_values>. In other words if
212 you define your condition coderef as:
213
214   sub {
215     my $args = shift;
216
217     return (
218       {
219         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
220         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
221       },
222       ! $args->{self_result_object} ? () : {
223         "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
224         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
225       },
226       ! $args->{foreign_values} ? () : {
227         "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
228       }
229     );
230   }
231
232 Then this code:
233
234     my $artist = $schema->resultset("Artist")->find({ id => 4 });
235     $artist->cds_80s->all;
236
237 Can skip a C<JOIN> altogether and instead produce:
238
239     SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
240       FROM cd cds_80s
241       WHERE cds_80s.artist = ?
242         AND cds_80s.year < ?
243         AND cds_80s.year > ?
244
245 With the bind values:
246
247     '4', '1990', '1979'
248
249 While this code:
250
251     my $cd = $schema->resultset("CD")->search({ artist => 1 }, { rows => 1 })->single;
252     my $artist = $schema->resultset("Artist")->new({});
253     $artist->set_from_related('cds_80s');
254
255 Will properly set the C<< $artist->artistid >> field of this new object to C<1>
256
257 Note that in order to be able to use L</set_from_related> (and by extension
258 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>),
259 the returned join free condition B<must> contain only plain values/deflatable
260 objects. For instance the C<year> constraint in the above example prevents
261 the relationship from being used to create related objects using
262 C<< $artst->create_related( cds_80s => { title => 'blah' } ) >> (an
263 exception will be thrown).
264
265 In order to allow the user to go truly crazy when generating a custom C<ON>
266 clause, the C<$args> hashref passed to the subroutine contains some extra
267 metadata. Currently the supplied coderef is executed as:
268
269   $relationship_info->{cond}->({
270     self_resultsource   => The resultsource instance on which rel_name is registered
271     rel_name            => The relationship name (does *NOT* always match foreign_alias)
272
273     self_alias          => The alias of the invoking resultset
274     foreign_alias       => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
275
276     # only one of these (or none at all) will ever be supplied to aid in the
277     # construction of a join-free condition
278
279     self_result_object  => The invocant *object* itself in case of a call like
280                            $result_object->$rel_name( ... )
281
282     foreign_values      => A *hashref* of related data: may be passed in directly or
283                            derived via ->get_columns() from a related object in case of
284                            $result_object->set_from_related( $rel_name, $foreign_result_object )
285
286     # deprecated inconsistent names, will be forever available for legacy code
287     self_rowobj         => Old deprecated slot for self_result_object
288     foreign_relname     => Old deprecated slot for rel_name
289   });
290
291 =head3 attributes
292
293 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
294 be used as relationship attributes. In particular, the 'where' attribute is
295 useful for filtering relationships:
296
297      __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
298         { 'foreign.user_id' => 'self.user_id' },
299         { where => { valid => 1 } }
300     );
301
302 The following attributes are also valid:
303
304 =over 4
305
306 =item join_type
307
308 Explicitly specifies the type of join to use in the relationship. Any SQL
309 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
310 command immediately before C<JOIN>.
311
312 =item proxy =E<gt> $column | \@columns | \%column
313
314 The 'proxy' attribute can be used to retrieve values, and to perform
315 updates if the relationship has 'cascade_update' set. The 'might_have'
316 and 'has_one' relationships have this set by default; if you want a proxy
317 to update across a 'belongs_to' relationship, you must set the attribute
318 yourself.
319
320 =over 4
321
322 =item \@columns
323
324 An arrayref containing a list of accessors in the foreign class to create in
325 the main class. If, for example, you do the following:
326
327   MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
328     undef, {
329       proxy => [ qw/notes/ ],
330     });
331
332 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
333
334   my $cd = MyApp::Schema::CD->find(1);
335   $cd->notes('Notes go here'); # set notes -- LinerNotes object is
336                                # created if it doesn't exist
337
338 For a 'belongs_to relationship, note the 'cascade_update':
339
340   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
341       { proxy => ['title'], cascade_update => 1 }
342   );
343   $track->title('New Title');
344   $track->update; # updates title in CD
345
346 =item \%column
347
348 A hashref where each key is the accessor you want installed in the main class,
349 and its value is the name of the original in the foreign class.
350
351   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
352       proxy => { cd_title => 'title' },
353   });
354
355 This will create an accessor named C<cd_title> on the C<$track> result object.
356
357 =back
358
359 NOTE: you can pass a nested struct too, for example:
360
361   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
362     proxy => [ 'year', { cd_title => 'title' } ],
363   });
364
365 =item accessor
366
367 Specifies the type of accessor that should be created for the relationship.
368 Valid values are C<single> (for when there is only a single related object),
369 C<multi> (when there can be many), and C<filter> (for when there is a single
370 related object, but you also want the relationship accessor to double as
371 a column accessor). For C<multi> accessors, an add_to_* method is also
372 created, which calls C<create_related> for the relationship.
373
374 =item is_foreign_key_constraint
375
376 If you are using L<SQL::Translator> to create SQL for you and you find that it
377 is creating constraints where it shouldn't, or not creating them where it
378 should, set this attribute to a true or false value to override the detection
379 of when to create constraints.
380
381 =item cascade_copy
382
383 If C<cascade_copy> is true on a C<has_many> relationship for an
384 object, then when you copy the object all the related objects will
385 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
386 in the C<$attr> hashref.
387
388 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
389 relationships.
390
391 =item cascade_delete
392
393 By default, DBIx::Class cascades deletes across C<has_many>,
394 C<has_one> and C<might_have> relationships. You can disable this
395 behaviour on a per-relationship basis by supplying
396 C<< cascade_delete => 0 >> in the relationship attributes.
397
398 The cascaded operations are performed after the requested delete,
399 so if your database has a constraint on the relationship, it will
400 have deleted/updated the related records or raised an exception
401 before DBIx::Class gets to perform the cascaded operation.
402
403 =item cascade_update
404
405 By default, DBIx::Class cascades updates across C<has_one> and
406 C<might_have> relationships. You can disable this behaviour on a
407 per-relationship basis by supplying C<< cascade_update => 0 >> in
408 the relationship attributes.
409
410 The C<belongs_to> relationship does not update across relationships
411 by default, so if you have a 'proxy' attribute on a belongs_to and want to
412 use 'update' on it, you must set C<< cascade_update => 1 >>.
413
414 This is not a RDMS style cascade update - it purely means that when
415 an object has update called on it, all the related objects also
416 have update called. It will not change foreign keys automatically -
417 you must arrange to do this yourself.
418
419 =item on_delete / on_update
420
421 If you are using L<SQL::Translator> to create SQL for you, you can use these
422 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
423 type. If not supplied the SQLT parser will attempt to infer the constraint type by
424 interrogating the attributes of the B<opposite> relationship. For any 'multi'
425 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
426 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
427 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
428 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
429 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
430 C<< on_delete => '' >>, and the same for C<on_update> respectively.
431
432 =item is_deferrable
433
434 Tells L<SQL::Translator> that the foreign key constraint it creates should be
435 deferrable. In other words, the user may request that the constraint be ignored
436 until the end of the transaction. Currently, only the PostgreSQL producer
437 actually supports this.
438
439 =item add_fk_index
440
441 Tells L<SQL::Translator> to add an index for this constraint. Can also be
442 specified globally in the args to L<DBIx::Class::Schema/deploy> or
443 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
444
445 =back
446
447 =head2 register_relationship
448
449 =over 4
450
451 =item Arguments: $rel_name, $rel_info
452
453 =back
454
455 Registers a relationship on the class. This is called internally by
456 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
457
458 =cut
459
460 sub register_relationship { }
461
462 =head2 related_resultset
463
464 =over 4
465
466 =item Arguments: $rel_name
467
468 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
469
470 =back
471
472   $rs = $cd->related_resultset('artist');
473
474 Returns a L<DBIx::Class::ResultSet> for the relationship named
475 $rel_name.
476
477 =head2 $relationship_accessor
478
479 =over 4
480
481 =item Arguments: none
482
483 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
484
485 =back
486
487   # These pairs do the same thing
488   $result = $cd->related_resultset('artist')->single;  # has_one relationship
489   $result = $cd->artist;
490   $rs = $cd->related_resultset('tracks');           # has_many relationship
491   $rs = $cd->tracks;
492
493 This is the recommended way to traverse through relationships, based
494 on the L</accessor> name given in the relationship definition.
495
496 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
497 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
498 C<single> (returns only one row) or C<multi> (returns many rows).  The
499 method may also return C<undef> if the relationship doesn't exist for
500 this instance (like in the case of C<might_have> relationships).
501
502 =cut
503
504 sub related_resultset {
505   $_[0]->throw_exception(
506     '$result->related_resultset() no longer accepts extra search arguments, '
507   . 'you need to switch to ...->related_resultset($relname)->search_rs(...) '
508   . 'instead (it was never documented and more importantly could never work '
509   . 'reliably due to the heavy caching involved)'
510   ) if @_ > 2;
511
512   $_[0]->throw_exception("Can't call *_related as class methods")
513     unless ref $_[0];
514
515   return $_[0]->{related_resultsets}{$_[1]}
516     if defined $_[0]->{related_resultsets}{$_[1]};
517
518   my ($self, $rel) = @_;
519
520   my $rsrc = $self->result_source;
521
522   my $rel_info = $rsrc->relationship_info($rel)
523     or $self->throw_exception( "No such relationship '$rel'" );
524
525   my $relcond_is_freeform = ref $rel_info->{cond} eq 'CODE';
526
527   my $jfc = $rsrc->_resolve_relationship_condition(
528
529     rel_name => $rel,
530     self_result_object => $self,
531
532     # an extra sanity check guard
533     require_join_free_condition => ! $relcond_is_freeform,
534
535     # an API where these are optional would be too cumbersome,
536     # instead always pass in some dummy values
537     DUMMY_ALIASPAIR,
538
539     # this may look weird, but remember that we are making a resultset
540     # out of an existing object, with the new source being at the head
541     # of the FROM chain. Having a 'me' alias is nothing but expected there
542     foreign_alias => 'me',
543
544   )->{join_free_condition};
545
546   my $rel_rset;
547
548   if (
549     ! $jfc
550       and
551     $relcond_is_freeform
552   ) {
553
554     # A WHOREIFFIC hack to reinvoke the entire condition resolution
555     # with the correct alias. Another way of doing this involves a
556     # lot of state passing around, and the @_ positions are already
557     # mapped out, making this crap a less icky option.
558     #
559     # The point of this exercise is to retain the spirit of the original
560     # $obj->search_related($rel) where the resulting rset will have the
561     # root alias as 'me', instead of $rel (as opposed to invoking
562     # $rs->search_related)
563
564     # make the fake 'me' rel
565     local $rsrc->{_relationships}{me} = {
566       %{ $rsrc->{_relationships}{$rel} },
567       _original_name => $rel,
568     };
569
570     my $obj_table_alias = lc($rsrc->source_name) . '__row';
571     $obj_table_alias =~ s/\W+/_/g;
572
573     $rel_rset = $rsrc->resultset->search(
574       $self->ident_condition($obj_table_alias),
575       { alias => $obj_table_alias },
576     )->related_resultset('me')->search(undef, $rel_info->{attrs})
577   }
578   else {
579
580     # FIXME - this conditional doesn't seem correct - got to figure out
581     # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
582     # business seems shady - we could simply not query *at all*
583     my $attrs;
584     if ( $jfc eq UNRESOLVABLE_CONDITION ) {
585       $attrs = { %{$rel_info->{attrs}} };
586       my $reverse = $rsrc->reverse_relationship_info($rel);
587       foreach my $rev_rel (keys %$reverse) {
588         if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
589           weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
590         } else {
591           weaken($attrs->{related_objects}{$rev_rel} = $self);
592         }
593       }
594     }
595
596     $rel_rset = $rsrc->related_source($rel)->resultset->search(
597       $jfc,
598       $attrs || $rel_info->{attrs},
599     );
600   }
601
602   $self->{related_resultsets}{$rel} = $rel_rset;
603 }
604
605 =head2 search_related
606
607 =over 4
608
609 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
610
611 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
612
613 =back
614
615 Run a search on a related resultset. The search will be restricted to the
616 results represented by the L<DBIx::Class::ResultSet> it was called
617 upon.
618
619 See L<DBIx::Class::ResultSet/search_related> for more information.
620
621 =cut
622
623 sub search_related :DBIC_method_is_indirect_sugar {
624   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
625   shift->related_resultset(shift)->search(@_);
626 }
627
628 =head2 search_related_rs
629
630 This method works exactly the same as search_related, except that
631 it guarantees a resultset, even in list context.
632
633 =cut
634
635 sub search_related_rs :DBIC_method_is_indirect_sugar {
636   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
637   shift->related_resultset(shift)->search_rs(@_)
638 }
639
640 =head2 count_related
641
642 =over 4
643
644 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
645
646 =item Return Value: $count
647
648 =back
649
650 Returns the count of all the rows in the related resultset, restricted by the
651 current result or where conditions.
652
653 =cut
654
655 sub count_related :DBIC_method_is_indirect_sugar {
656   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
657   shift->related_resultset(shift)->search_rs(@_)->count;
658 }
659
660 =head2 new_related
661
662 =over 4
663
664 =item Arguments: $rel_name, \%col_data
665
666 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
667
668 =back
669
670 Create a new result object of the related foreign class.  It will magically set
671 any foreign key columns of the new object to the related primary key columns
672 of the source object for you.  The newly created result will not be saved into
673 your storage until you call L<DBIx::Class::Row/insert> on it.
674
675 =cut
676
677 sub new_related {
678   my ($self, $rel, $data) = @_;
679
680   $self->related_resultset($rel)->new_result( $self->result_source->_resolve_relationship_condition (
681     infer_values_based_on => $data,
682     rel_name => $rel,
683     self_result_object => $self,
684
685     # an API where these are optional would be too cumbersome,
686     # instead always pass in some dummy values
687     DUMMY_ALIASPAIR,
688
689   )->{inferred_values} );
690 }
691
692 =head2 create_related
693
694 =over 4
695
696 =item Arguments: $rel_name, \%col_data
697
698 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
699
700 =back
701
702   my $result = $obj->create_related($rel_name, \%col_data);
703
704 Creates a new result object, similarly to new_related, and also inserts the
705 result's data into your storage medium. See the distinction between C<create>
706 and C<new> in L<DBIx::Class::ResultSet> for details.
707
708 =cut
709
710 sub create_related {
711   my $self = shift;
712   my $rel = shift;
713   my $obj = $self->new_related($rel, @_)->insert;
714   delete $self->{related_resultsets}->{$rel};
715   return $obj;
716 }
717
718 =head2 find_related
719
720 =over 4
721
722 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
723
724 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
725
726 =back
727
728   my $result = $obj->find_related($rel_name, \%col_data);
729
730 Attempt to find a related object using its primary key or unique constraints.
731 See L<DBIx::Class::ResultSet/find> for details.
732
733 =cut
734
735 sub find_related :DBIC_method_is_indirect_sugar {
736   #my ($self, $rel, @args) = @_;
737   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
738   return shift->related_resultset(shift)->find(@_);
739 }
740
741 =head2 find_or_new_related
742
743 =over 4
744
745 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
746
747 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
748
749 =back
750
751 Find a result object of a related class.  See L<DBIx::Class::ResultSet/find_or_new>
752 for details.
753
754 =cut
755
756 sub find_or_new_related {
757   my $self = shift;
758   my $rel = shift;
759   my $obj = $self->related_resultset($rel)->find(@_);
760   return defined $obj ? $obj : $self->related_resultset($rel)->new_result(@_);
761 }
762
763 =head2 find_or_create_related
764
765 =over 4
766
767 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
768
769 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
770
771 =back
772
773 Find or create a result object of a related class. See
774 L<DBIx::Class::ResultSet/find_or_create> for details.
775
776 =cut
777
778 sub find_or_create_related {
779   my $self = shift;
780   my $rel = shift;
781   my $obj = $self->related_resultset($rel)->find(@_);
782   return (defined($obj) ? $obj : $self->create_related( $rel => @_ ));
783 }
784
785 =head2 update_or_create_related
786
787 =over 4
788
789 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
790
791 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
792
793 =back
794
795 Update or create a result object of a related class. See
796 L<DBIx::Class::ResultSet/update_or_create> for details.
797
798 =cut
799
800 sub update_or_create_related :DBIC_method_is_indirect_sugar {
801   #my ($self, $rel, @args) = @_;
802   DBIx::Class::_ENV_::ASSERT_NO_INTERNAL_INDIRECT_CALLS and fail_on_internal_call;
803   shift->related_resultset(shift)->update_or_create(@_);
804 }
805
806 =head2 set_from_related
807
808 =over 4
809
810 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
811
812 =item Return Value: not defined
813
814 =back
815
816   $book->set_from_related('author', $author_obj);
817   $book->author($author_obj);                      ## same thing
818
819 Set column values on the current object, using related values from the given
820 related object. This is used to associate previously separate objects, for
821 example, to set the correct author for a book, find the Author object, then
822 call set_from_related on the book.
823
824 This is called internally when you pass existing objects as values to
825 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
826
827 The columns are only set in the local copy of the object, call
828 L<update|DBIx::Class::Row/update> to update them in the storage.
829
830 =cut
831
832 sub set_from_related {
833   my ($self, $rel, $f_obj) = @_;
834
835   $self->set_columns( $self->result_source->_resolve_relationship_condition (
836     infer_values_based_on => {},
837     rel_name => $rel,
838     foreign_values => (
839       # maintain crazy set_from_related interface
840       #
841       ( ! defined $f_obj )          ? +{}
842     : ( ! defined blessed $f_obj )  ? $f_obj
843                                     : do {
844
845         my $f_result_class = $self->result_source->related_source($rel)->result_class;
846
847         unless( $f_obj->isa($f_result_class) ) {
848
849           $self->throw_exception(
850             'Object supplied to set_from_related() must inherit from '
851           . "'$DBIx::Class::ResultSource::__expected_result_class_isa'"
852           ) unless $f_obj->isa(
853             $DBIx::Class::ResultSource::__expected_result_class_isa
854           );
855
856           carp_unique(
857             'Object supplied to set_from_related() usually should inherit from '
858           . "the related ResultClass ('$f_result_class'), perhaps you've made "
859           . 'a mistake?'
860           );
861         }
862
863         +{ $f_obj->get_columns };
864       }
865     ),
866
867     # an API where these are optional would be too cumbersome,
868     # instead always pass in some dummy values
869     DUMMY_ALIASPAIR,
870
871   )->{inferred_values} );
872
873   return 1;
874 }
875
876 =head2 update_from_related
877
878 =over 4
879
880 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
881
882 =item Return Value: not defined
883
884 =back
885
886   $book->update_from_related('author', $author_obj);
887
888 The same as L</"set_from_related">, but the changes are immediately updated
889 in storage.
890
891 =cut
892
893 sub update_from_related {
894   my $self = shift;
895   $self->set_from_related(@_);
896   $self->update;
897 }
898
899 =head2 delete_related
900
901 =over 4
902
903 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
904
905 =item Return Value: $underlying_storage_rv
906
907 =back
908
909 Delete any related row, subject to the given conditions.  Internally, this
910 calls:
911
912   $self->search_related(@_)->delete
913
914 And returns the result of that.
915
916 =cut
917
918 sub delete_related {
919   my $self = shift;
920   my $rel = shift;
921   my $obj = $self->related_resultset($rel)->search_rs(@_)->delete;
922   delete $self->{related_resultsets}->{$rel};
923   return $obj;
924 }
925
926 =head2 add_to_$rel
927
928 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
929 relationships.>
930
931 =head3 has_many / multi
932
933 =over 4
934
935 =item Arguments: \%col_data
936
937 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
938
939 =back
940
941 Creates/inserts a new result object.  Internally, this calls:
942
943   $self->create_related($rel, @_)
944
945 And returns the result of that.
946
947 =head3 many_to_many
948
949 =over 4
950
951 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
952
953 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
954
955 =back
956
957   my $role = $schema->resultset('Role')->find(1);
958   $actor->add_to_roles($role);
959       # creates a My::DBIC::Schema::ActorRoles linking table result object
960
961   $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
962       # creates a new My::DBIC::Schema::Role result object and the linking table
963       # object with an extra column in the link
964
965 Adds a linking table object. If the first argument is a hash reference, the
966 related object is created first with the column values in the hash. If an object
967 reference is given, just the linking table object is created. In either case,
968 any additional column values for the linking table object can be specified in
969 C<\%link_col_data>.
970
971 See L<DBIx::Class::Relationship/many_to_many> for additional details.
972
973 =head2 set_$rel
974
975 B<Currently only available for C<many_to_many> relationships.>
976
977 =over 4
978
979 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
980
981 =item Return Value: not defined
982
983 =back
984
985   my $actor = $schema->resultset('Actor')->find(1);
986   my @roles = $schema->resultset('Role')->search({ role =>
987      { '-in' => ['Fred', 'Barney'] } } );
988
989   $actor->set_roles(\@roles);
990      # Replaces all of $actor's previous roles with the two named
991
992   $actor->set_roles(\@roles, { salary => 15_000_000 });
993      # Sets a column in the link table for all roles
994
995
996 Replace all the related objects with the given reference to a list of
997 objects. This does a C<delete> B<on the link table resultset> to remove the
998 association between the current object and all related objects, then calls
999 C<add_to_$rel> repeatedly to link all the new objects.
1000
1001 Note that this means that this method will B<not> delete any objects in the
1002 table on the right side of the relation, merely that it will delete the link
1003 between them.
1004
1005 Due to a mistake in the original implementation of this method, it will also
1006 accept a list of objects or hash references. This is B<deprecated> and will be
1007 removed in a future version.
1008
1009 =head2 remove_from_$rel
1010
1011 B<Currently only available for C<many_to_many> relationships.>
1012
1013 =over 4
1014
1015 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
1016
1017 =item Return Value: not defined
1018
1019 =back
1020
1021   my $role = $schema->resultset('Role')->find(1);
1022   $actor->remove_from_roles($role);
1023       # removes $role's My::DBIC::Schema::ActorRoles linking table result object
1024
1025 Removes the link between the current object and the related object. Note that
1026 the related object itself won't be deleted unless you call ->delete() on
1027 it. This method just removes the link between the two objects.
1028
1029 =head1 FURTHER QUESTIONS?
1030
1031 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
1032
1033 =head1 COPYRIGHT AND LICENSE
1034
1035 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
1036 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
1037 redistribute it and/or modify it under the same terms as the
1038 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
1039
1040 =cut
1041
1042 1;