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