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