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