e11263fbaa52f37ad6e9cdbc1bc4803bd8a64b28
[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 Try::Tiny;
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 join-free condition hashref when
184 invoked as C<< $result->relationship >>, as opposed to
185 C<< $rs->related_resultset('relationship') >>. In this case C<$result> is
186 passed to the coderef as C<< $args->{self_rowobj} >>, so a user can do the
187 following:
188
189   sub {
190     my $args = shift;
191
192     return (
193       {
194         "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
195         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
196       },
197       $args->{self_rowobj} && {
198         "$args->{foreign_alias}.artist" => $args->{self_rowobj}->artistid,
199         "$args->{foreign_alias}.year"   => { '>', "1979", '<', "1990" },
200       },
201     );
202   }
203
204 Now this code:
205
206     my $artist = $schema->resultset("Artist")->find({ id => 4 });
207     $artist->cds_80s->all;
208
209 Can skip a C<JOIN> altogether and instead produce:
210
211     SELECT cds_80s.cdid, cds_80s.artist, cds_80s.title, cds_80s.year, cds_80s.genreid, cds_80s.single_track
212       FROM cd cds_80s
213       WHERE cds_80s.artist = ?
214         AND cds_80s.year < ?
215         AND cds_80s.year > ?
216
217 With the bind values:
218
219     '4', '1990', '1979'
220
221 Note that in order to be able to use
222 L<< $result->create_related|DBIx::Class::Relationship::Base/create_related >>,
223 the coderef must not only return as its second such a "simple" condition
224 hashref which does not depend on joins being available, but the hashref must
225 contain only plain values/deflatable objects, such that the result can be
226 passed directly to L<DBIx::Class::Relationship::Base/set_from_related>. For
227 instance the C<year> constraint in the above example prevents the relationship
228 from being used to create related objects (an exception will be thrown).
229
230 In order to allow the user to go truly crazy when generating a custom C<ON>
231 clause, the C<$args> hashref passed to the subroutine contains some extra
232 metadata. Currently the supplied coderef is executed as:
233
234   $relationship_info->{cond}->({
235     self_resultsource => The resultsource instance on which rel_name is registered
236     rel_name          => The relationship name (does *NOT* always match foreign_alias)
237
238     self_alias        => The alias of the invoking resultset
239     foreign_alias     => The alias of the to-be-joined resultset (does *NOT* always match rel_name)
240
241     # only one of these (or none at all) will ever be supplied to aid in the
242     # construction of a join-free condition
243     self_resultobj    => The invocant object itself in case of a $resultobj->$rel_name() call
244     foreign_resultobj => The related object in case of $resultobj->set_from_related($rel_name, $foreign_resultobj)
245
246     # deprecated inconsistent names, will be forever available for legacy code
247     self_rowobj       => Old deprecated slot for self_resultobj
248     foreign_relname   => Old deprecated slot for rel_name
249   });
250
251 =head3 attributes
252
253 The L<standard ResultSet attributes|DBIx::Class::ResultSet/ATTRIBUTES> may
254 be used as relationship attributes. In particular, the 'where' attribute is
255 useful for filtering relationships:
256
257      __PACKAGE__->has_many( 'valid_users', 'MyApp::Schema::User',
258         { 'foreign.user_id' => 'self.user_id' },
259         { where => { valid => 1 } }
260     );
261
262 The following attributes are also valid:
263
264 =over 4
265
266 =item join_type
267
268 Explicitly specifies the type of join to use in the relationship. Any SQL
269 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
270 command immediately before C<JOIN>.
271
272 =item proxy =E<gt> $column | \@columns | \%column
273
274 The 'proxy' attribute can be used to retrieve values, and to perform
275 updates if the relationship has 'cascade_update' set. The 'might_have'
276 and 'has_one' relationships have this set by default; if you want a proxy
277 to update across a 'belongs_to' relationship, you must set the attribute
278 yourself.
279
280 =over 4
281
282 =item \@columns
283
284 An arrayref containing a list of accessors in the foreign class to create in
285 the main class. If, for example, you do the following:
286
287   MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
288     undef, {
289       proxy => [ qw/notes/ ],
290     });
291
292 Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
293
294   my $cd = MyApp::Schema::CD->find(1);
295   $cd->notes('Notes go here'); # set notes -- LinerNotes object is
296                                # created if it doesn't exist
297
298 For a 'belongs_to relationship, note the 'cascade_update':
299
300   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
301       { proxy => ['title'], cascade_update => 1 }
302   );
303   $track->title('New Title');
304   $track->update; # updates title in CD
305
306 =item \%column
307
308 A hashref where each key is the accessor you want installed in the main class,
309 and its value is the name of the original in the foreign class.
310
311   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
312       proxy => { cd_title => 'title' },
313   });
314
315 This will create an accessor named C<cd_title> on the C<$track> result object.
316
317 =back
318
319 NOTE: you can pass a nested struct too, for example:
320
321   MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
322     proxy => [ 'year', { cd_title => 'title' } ],
323   });
324
325 =item accessor
326
327 Specifies the type of accessor that should be created for the relationship.
328 Valid values are C<single> (for when there is only a single related object),
329 C<multi> (when there can be many), and C<filter> (for when there is a single
330 related object, but you also want the relationship accessor to double as
331 a column accessor). For C<multi> accessors, an add_to_* method is also
332 created, which calls C<create_related> for the relationship.
333
334 =item is_foreign_key_constraint
335
336 If you are using L<SQL::Translator> to create SQL for you and you find that it
337 is creating constraints where it shouldn't, or not creating them where it
338 should, set this attribute to a true or false value to override the detection
339 of when to create constraints.
340
341 =item cascade_copy
342
343 If C<cascade_copy> is true on a C<has_many> relationship for an
344 object, then when you copy the object all the related objects will
345 be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
346 in the C<$attr> hashref.
347
348 The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
349 relationships.
350
351 =item cascade_delete
352
353 By default, DBIx::Class cascades deletes across C<has_many>,
354 C<has_one> and C<might_have> relationships. You can disable this
355 behaviour on a per-relationship basis by supplying
356 C<< cascade_delete => 0 >> in the relationship attributes.
357
358 The cascaded operations are performed after the requested delete,
359 so if your database has a constraint on the relationship, it will
360 have deleted/updated the related records or raised an exception
361 before DBIx::Class gets to perform the cascaded operation.
362
363 =item cascade_update
364
365 By default, DBIx::Class cascades updates across C<has_one> and
366 C<might_have> relationships. You can disable this behaviour on a
367 per-relationship basis by supplying C<< cascade_update => 0 >> in
368 the relationship attributes.
369
370 The C<belongs_to> relationship does not update across relationships
371 by default, so if you have a 'proxy' attribute on a belongs_to and want to
372 use 'update' on it, you muse set C<< cascade_update => 1 >>.
373
374 This is not a RDMS style cascade update - it purely means that when
375 an object has update called on it, all the related objects also
376 have update called. It will not change foreign keys automatically -
377 you must arrange to do this yourself.
378
379 =item on_delete / on_update
380
381 If you are using L<SQL::Translator> to create SQL for you, you can use these
382 attributes to explicitly set the desired C<ON DELETE> or C<ON UPDATE> constraint
383 type. If not supplied the SQLT parser will attempt to infer the constraint type by
384 interrogating the attributes of the B<opposite> relationship. For any 'multi'
385 relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
386 relationship will be created with an C<ON DELETE CASCADE> constraint. For any
387 relationship bearing C<< cascade_copy => 1 >> the resulting belongs_to constraint
388 will be C<ON UPDATE CASCADE>. If you wish to disable this autodetection, and just
389 use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
390 C<< on_delete => '' >>, and the same for C<on_update> respectively.
391
392 =item is_deferrable
393
394 Tells L<SQL::Translator> that the foreign key constraint it creates should be
395 deferrable. In other words, the user may request that the constraint be ignored
396 until the end of the transaction. Currently, only the PostgreSQL producer
397 actually supports this.
398
399 =item add_fk_index
400
401 Tells L<SQL::Translator> to add an index for this constraint. Can also be
402 specified globally in the args to L<DBIx::Class::Schema/deploy> or
403 L<DBIx::Class::Schema/create_ddl_dir>. Default is on, set to 0 to disable.
404
405 =back
406
407 =head2 register_relationship
408
409 =over 4
410
411 =item Arguments: $rel_name, $rel_info
412
413 =back
414
415 Registers a relationship on the class. This is called internally by
416 DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
417
418 =cut
419
420 sub register_relationship { }
421
422 =head2 related_resultset
423
424 =over 4
425
426 =item Arguments: $rel_name
427
428 =item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
429
430 =back
431
432   $rs = $cd->related_resultset('artist');
433
434 Returns a L<DBIx::Class::ResultSet> for the relationship named
435 $rel_name.
436
437 =head2 $relationship_accessor
438
439 =over 4
440
441 =item Arguments: none
442
443 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
444
445 =back
446
447   # These pairs do the same thing
448   $result = $cd->related_resultset('artist')->single;  # has_one relationship
449   $result = $cd->artist;
450   $rs = $cd->related_resultset('tracks');           # has_many relationship
451   $rs = $cd->tracks;
452
453 This is the recommended way to traverse through relationships, based
454 on the L</accessor> name given in the relationship definition.
455
456 This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
457 L<ResultSet|DBIx::Class::ResultSet>, depending on if the relationship is
458 C<single> (returns only one row) or C<multi> (returns many rows).  The
459 method may also return C<undef> if the relationship doesn't exist for
460 this instance (like in the case of C<might_have> relationships).
461
462 =cut
463
464 sub related_resultset {
465   my $self = shift;
466
467   $self->throw_exception("Can't call *_related as class methods")
468     unless ref $self;
469
470   my $rel = shift;
471
472   return $self->{related_resultsets}{$rel}
473     if defined $self->{related_resultsets}{$rel};
474
475   return $self->{related_resultsets}{$rel} = do {
476
477     my $rel_info = $self->relationship_info($rel)
478       or $self->throw_exception( "No such relationship '$rel'" );
479
480     my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
481     $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
482
483     $self->throw_exception( "Invalid query: @_" )
484       if (@_ > 1 && (@_ % 2 == 1));
485     my $query = ((@_ > 1) ? {@_} : shift);
486
487     my $rsrc = $self->result_source;
488
489     # condition resolution may fail if an incomplete master-object prefetch
490     # is encountered - that is ok during prefetch construction (not yet in_storage)
491     my ($cond, $is_crosstable) = try {
492       $rsrc->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel )
493     }
494     catch {
495       $self->throw_exception ($_) if $self->in_storage;
496       $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION;  # RV, no return()
497     };
498
499     # keep in mind that the following if() block is part of a do{} - no return()s!!!
500     if ($is_crosstable and ref $rel_info->{cond} eq 'CODE') {
501
502       # A WHOREIFFIC hack to reinvoke the entire condition resolution
503       # with the correct alias. Another way of doing this involves a
504       # lot of state passing around, and the @_ positions are already
505       # mapped out, making this crap a less icky option.
506       #
507       # The point of this exercise is to retain the spirit of the original
508       # $obj->search_related($rel) where the resulting rset will have the
509       # root alias as 'me', instead of $rel (as opposed to invoking
510       # $rs->search_related)
511
512       local $rsrc->{_relationships}{me} = $rsrc->{_relationships}{$rel};  # make the fake 'me' rel
513       my $obj_table_alias = lc($rsrc->source_name) . '__row';
514       $obj_table_alias =~ s/\W+/_/g;
515
516       $rsrc->resultset->search(
517         $self->ident_condition($obj_table_alias),
518         { alias => $obj_table_alias },
519       )->search_related('me', $query, $attrs)
520     }
521     else {
522       # FIXME - this conditional doesn't seem correct - got to figure out
523       # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
524       # business seems shady - we could simply not query *at all*
525       if ($cond eq $DBIx::Class::ResultSource::UNRESOLVABLE_CONDITION) {
526         my $reverse = $rsrc->reverse_relationship_info($rel);
527         foreach my $rev_rel (keys %$reverse) {
528           if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
529             weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
530           } else {
531             weaken($attrs->{related_objects}{$rev_rel} = $self);
532           }
533         }
534       }
535       elsif (ref $cond eq 'ARRAY') {
536         $cond = [ map {
537           if (ref $_ eq 'HASH') {
538             my $hash;
539             foreach my $key (keys %$_) {
540               my $newkey = $key !~ /\./ ? "me.$key" : $key;
541               $hash->{$newkey} = $_->{$key};
542             }
543             $hash;
544           } else {
545             $_;
546           }
547         } @$cond ];
548       }
549       elsif (ref $cond eq 'HASH') {
550        foreach my $key (grep { ! /\./ } keys %$cond) {
551           $cond->{"me.$key"} = delete $cond->{$key};
552         }
553       }
554
555       $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
556       $rsrc->related_source($rel)->resultset->search(
557         $query, $attrs
558       );
559     }
560   };
561 }
562
563 =head2 search_related
564
565 =over 4
566
567 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
568
569 =item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
570
571 =back
572
573 Run a search on a related resultset. The search will be restricted to the
574 results represented by the L<DBIx::Class::ResultSet> it was called
575 upon.
576
577 See L<DBIx::Class::ResultSet/search_related> for more information.
578
579 =cut
580
581 sub search_related {
582   return shift->related_resultset(shift)->search(@_);
583 }
584
585 =head2 search_related_rs
586
587 This method works exactly the same as search_related, except that
588 it guarantees a resultset, even in list context.
589
590 =cut
591
592 sub search_related_rs {
593   return shift->related_resultset(shift)->search_rs(@_);
594 }
595
596 =head2 count_related
597
598 =over 4
599
600 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
601
602 =item Return Value: $count
603
604 =back
605
606 Returns the count of all the rows in the related resultset, restricted by the
607 current result or where conditions.
608
609 =cut
610
611 sub count_related {
612   shift->search_related(@_)->count;
613 }
614
615 =head2 new_related
616
617 =over 4
618
619 =item Arguments: $rel_name, \%col_data
620
621 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
622
623 =back
624
625 Create a new result object of the related foreign class.  It will magically set
626 any foreign key columns of the new object to the related primary key columns
627 of the source object for you.  The newly created result will not be saved into
628 your storage until you call L<DBIx::Class::Row/insert> on it.
629
630 =cut
631
632 sub new_related {
633   my ($self, $rel, $values) = @_;
634
635   # FIXME - this is a bad position for this (also an identical copy in
636   # set_from_related), but I have no saner way to hook, and I absolutely
637   # want this to throw at least for coderefs, instead of the "insert a NULL
638   # when it gets hard" insanity --ribasushi
639   #
640   # sanity check - currently throw when a complex coderef rel is encountered
641   # FIXME - should THROW MOAR!
642
643   if (ref $self) {  # cdbi calls this as a class method, /me vomits
644
645     my $rsrc = $self->result_source;
646     my $rel_info = $rsrc->relationship_info($rel)
647       or $self->throw_exception( "No such relationship '$rel'" );
648     my (undef, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
649       $rel_info->{cond}, $rel, $self, $rel
650     );
651
652     $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
653       if $crosstable;
654
655     if (
656       $nonequality_foreign_columns
657         and
658       my @unspecified_rel_condition_chunks = grep { ! exists $values->{$_} } @$nonequality_foreign_columns
659     ) {
660       $self->throw_exception(sprintf (
661         "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
662         $rel,
663         map { "'$_'" } @unspecified_rel_condition_chunks
664       ));
665     }
666   }
667
668   return $self->search_related($rel)->new_result($values);
669 }
670
671 =head2 create_related
672
673 =over 4
674
675 =item Arguments: $rel_name, \%col_data
676
677 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
678
679 =back
680
681   my $result = $obj->create_related($rel_name, \%col_data);
682
683 Creates a new result object, similarly to new_related, and also inserts the
684 result's data into your storage medium. See the distinction between C<create>
685 and C<new> in L<DBIx::Class::ResultSet> for details.
686
687 =cut
688
689 sub create_related {
690   my $self = shift;
691   my $rel = shift;
692   my $obj = $self->new_related($rel, @_)->insert;
693   delete $self->{related_resultsets}->{$rel};
694   return $obj;
695 }
696
697 =head2 find_related
698
699 =over 4
700
701 =item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
702
703 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
704
705 =back
706
707   my $result = $obj->find_related($rel_name, \%col_data);
708
709 Attempt to find a related object using its primary key or unique constraints.
710 See L<DBIx::Class::ResultSet/find> for details.
711
712 =cut
713
714 sub find_related {
715   #my ($self, $rel, @args) = @_;
716   return shift->search_related(shift)->find(@_);
717 }
718
719 =head2 find_or_new_related
720
721 =over 4
722
723 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
724
725 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
726
727 =back
728
729 Find a result object of a related class.  See L<DBIx::Class::ResultSet/find_or_new>
730 for details.
731
732 =cut
733
734 sub find_or_new_related {
735   my $self = shift;
736   my $obj = $self->find_related(@_);
737   return defined $obj ? $obj : $self->new_related(@_);
738 }
739
740 =head2 find_or_create_related
741
742 =over 4
743
744 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
745
746 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
747
748 =back
749
750 Find or create a result object of a related class. See
751 L<DBIx::Class::ResultSet/find_or_create> for details.
752
753 =cut
754
755 sub find_or_create_related {
756   my $self = shift;
757   my $obj = $self->find_related(@_);
758   return (defined($obj) ? $obj : $self->create_related(@_));
759 }
760
761 =head2 update_or_create_related
762
763 =over 4
764
765 =item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
766
767 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
768
769 =back
770
771 Update or create a result object of a related class. See
772 L<DBIx::Class::ResultSet/update_or_create> for details.
773
774 =cut
775
776 sub update_or_create_related {
777   #my ($self, $rel, @args) = @_;
778   shift->related_resultset(shift)->update_or_create(@_);
779 }
780
781 =head2 set_from_related
782
783 =over 4
784
785 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
786
787 =item Return Value: not defined
788
789 =back
790
791   $book->set_from_related('author', $author_obj);
792   $book->author($author_obj);                      ## same thing
793
794 Set column values on the current object, using related values from the given
795 related object. This is used to associate previously separate objects, for
796 example, to set the correct author for a book, find the Author object, then
797 call set_from_related on the book.
798
799 This is called internally when you pass existing objects as values to
800 L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
801
802 The columns are only set in the local copy of the object, call L</update> to
803 set them in the storage.
804
805 =cut
806
807 sub set_from_related {
808   my ($self, $rel, $f_obj) = @_;
809
810   my $rsrc = $self->result_source;
811   my $rel_info = $rsrc->relationship_info($rel)
812     or $self->throw_exception( "No such relationship '$rel'" );
813
814   if (defined $f_obj) {
815     my $f_class = $rel_info->{class};
816     $self->throw_exception( "Object '$f_obj' isn't a ".$f_class )
817       unless blessed $f_obj and $f_obj->isa($f_class);
818   }
819
820
821   # FIXME - this is a bad position for this (also an identical copy in
822   # new_related), but I have no saner way to hook, and I absolutely
823   # want this to throw at least for coderefs, instead of the "insert a NULL
824   # when it gets hard" insanity --ribasushi
825   #
826   # sanity check - currently throw when a complex coderef rel is encountered
827   # FIXME - should THROW MOAR!
828   my ($cond, $crosstable, $nonequality_foreign_columns) = $rsrc->_resolve_condition (
829     $rel_info->{cond}, $f_obj, $rel, $rel
830   );
831   $self->throw_exception("Relationship '$rel' does not resolve to a join-free condition fragment")
832     if $crosstable;
833
834   $self->throw_exception(sprintf (
835     "Custom relationship '%s' not definitive - returns conditions instead of values for column(s): %s",
836     $rel,
837     map { "'$_'" } @$nonequality_foreign_columns
838   )) if $nonequality_foreign_columns;
839
840   $self->set_columns($cond);
841
842   return 1;
843 }
844
845 =head2 update_from_related
846
847 =over 4
848
849 =item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
850
851 =item Return Value: not defined
852
853 =back
854
855   $book->update_from_related('author', $author_obj);
856
857 The same as L</"set_from_related">, but the changes are immediately updated
858 in storage.
859
860 =cut
861
862 sub update_from_related {
863   my $self = shift;
864   $self->set_from_related(@_);
865   $self->update;
866 }
867
868 =head2 delete_related
869
870 =over 4
871
872 =item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
873
874 =item Return Value: $underlying_storage_rv
875
876 =back
877
878 Delete any related row, subject to the given conditions.  Internally, this
879 calls:
880
881   $self->search_related(@_)->delete
882
883 And returns the result of that.
884
885 =cut
886
887 sub delete_related {
888   my $self = shift;
889   my $obj = $self->search_related(@_)->delete;
890   delete $self->{related_resultsets}->{$_[0]};
891   return $obj;
892 }
893
894 =head2 add_to_$rel
895
896 B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
897 relationships.>
898
899 =head3 has_many / multi
900
901 =over 4
902
903 =item Arguments: \%col_data
904
905 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
906
907 =back
908
909 Creates/inserts a new result object.  Internally, this calls:
910
911   $self->create_related($rel, @_)
912
913 And returns the result of that.
914
915 =head3 many_to_many
916
917 =over 4
918
919 =item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
920
921 =item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
922
923 =back
924
925   my $role = $schema->resultset('Role')->find(1);
926   $actor->add_to_roles($role);
927       # creates a My::DBIC::Schema::ActorRoles linking table result object
928
929   $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
930       # creates a new My::DBIC::Schema::Role result object and the linking table
931       # object with an extra column in the link
932
933 Adds a linking table object. If the first argument is a hash reference, the
934 related object is created first with the column values in the hash. If an object
935 reference is given, just the linking table object is created. In either case,
936 any additional column values for the linking table object can be specified in
937 C<\%link_col_data>.
938
939 See L<DBIx::Class::Relationship/many_to_many> for additional details.
940
941 =head2 set_$rel
942
943 B<Currently only available for C<many_to_many> relationships.>
944
945 =over 4
946
947 =item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
948
949 =item Return Value: not defined
950
951 =back
952
953   my $actor = $schema->resultset('Actor')->find(1);
954   my @roles = $schema->resultset('Role')->search({ role =>
955      { '-in' => ['Fred', 'Barney'] } } );
956
957   $actor->set_roles(\@roles);
958      # Replaces all of $actor's previous roles with the two named
959
960   $actor->set_roles(\@roles, { salary => 15_000_000 });
961      # Sets a column in the link table for all roles
962
963
964 Replace all the related objects with the given reference to a list of
965 objects. This does a C<delete> B<on the link table resultset> to remove the
966 association between the current object and all related objects, then calls
967 C<add_to_$rel> repeatedly to link all the new objects.
968
969 Note that this means that this method will B<not> delete any objects in the
970 table on the right side of the relation, merely that it will delete the link
971 between them.
972
973 Due to a mistake in the original implementation of this method, it will also
974 accept a list of objects or hash references. This is B<deprecated> and will be
975 removed in a future version.
976
977 =head2 remove_from_$rel
978
979 B<Currently only available for C<many_to_many> relationships.>
980
981 =over 4
982
983 =item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
984
985 =item Return Value: not defined
986
987 =back
988
989   my $role = $schema->resultset('Role')->find(1);
990   $actor->remove_from_roles($role);
991       # removes $role's My::DBIC::Schema::ActorRoles linking table result object
992
993 Removes the link between the current object and the related object. Note that
994 the related object itself won't be deleted unless you call ->delete() on
995 it. This method just removes the link between the two objects.
996
997 =head1 AUTHOR AND CONTRIBUTORS
998
999 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
1000
1001 =head1 LICENSE
1002
1003 You may distribute this code under the same terms as Perl itself.
1004
1005 =cut
1006
1007 1;