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