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