← Index
NYTProf Performance Profile   « line view »
For starman worker -M FindBin --max-requests 50 --workers 2 --user=kohadev-koha --group kohadev-koha --pid /var/run/koha/kohadev/plack.pid --daemonize --access-log /var/log/koha/kohadev/plack.log --error-log /var/log/koha/kohadev/plack-error.log -E deployment --socket /var/run/koha/kohadev/plack.sock /etc/koha/sites/kohadev/plack.psgi
  Run on Fri Jan 8 13:01:18 2016
Reported on Fri Jan 8 13:01:35 2016

Filename/usr/share/perl5/DBIx/Class/Relationship/Base.pm
StatementsExecuted 334 statements in 2.34ms
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
11114µs22µsDBIx::Class::Relationship::Base::::BEGIN@3DBIx::Class::Relationship::Base::BEGIN@3
11114µs37µsDBIx::Class::Relationship::Base::::BEGIN@9DBIx::Class::Relationship::Base::BEGIN@9
11113µs18µsDBIx::Class::Relationship::Base::::BEGIN@4DBIx::Class::Relationship::Base::BEGIN@4
11110µs36µsDBIx::Class::Relationship::Base::::BEGIN@8DBIx::Class::Relationship::Base::BEGIN@8
11110µs50µsDBIx::Class::Relationship::Base::::BEGIN@6DBIx::Class::Relationship::Base::BEGIN@6
1118µs22µsDBIx::Class::Relationship::Base::::BEGIN@10DBIx::Class::Relationship::Base::BEGIN@10
1118µs140µsDBIx::Class::Relationship::Base::::BEGIN@11DBIx::Class::Relationship::Base::BEGIN@11
0000s0sDBIx::Class::Relationship::Base::::__ANON__[:530]DBIx::Class::Relationship::Base::__ANON__[:530]
0000s0sDBIx::Class::Relationship::Base::::__ANON__[:534]DBIx::Class::Relationship::Base::__ANON__[:534]
0000s0sDBIx::Class::Relationship::Base::::count_relatedDBIx::Class::Relationship::Base::count_related
0000s0sDBIx::Class::Relationship::Base::::create_relatedDBIx::Class::Relationship::Base::create_related
0000s0sDBIx::Class::Relationship::Base::::delete_relatedDBIx::Class::Relationship::Base::delete_related
0000s0sDBIx::Class::Relationship::Base::::find_or_create_relatedDBIx::Class::Relationship::Base::find_or_create_related
0000s0sDBIx::Class::Relationship::Base::::find_or_new_relatedDBIx::Class::Relationship::Base::find_or_new_related
0000s0sDBIx::Class::Relationship::Base::::find_relatedDBIx::Class::Relationship::Base::find_related
0000s0sDBIx::Class::Relationship::Base::::new_relatedDBIx::Class::Relationship::Base::new_related
0000s0sDBIx::Class::Relationship::Base::::register_relationshipDBIx::Class::Relationship::Base::register_relationship
0000s0sDBIx::Class::Relationship::Base::::related_resultsetDBIx::Class::Relationship::Base::related_resultset
0000s0sDBIx::Class::Relationship::Base::::search_relatedDBIx::Class::Relationship::Base::search_related
0000s0sDBIx::Class::Relationship::Base::::search_related_rsDBIx::Class::Relationship::Base::search_related_rs
0000s0sDBIx::Class::Relationship::Base::::set_from_relatedDBIx::Class::Relationship::Base::set_from_related
0000s0sDBIx::Class::Relationship::Base::::update_from_relatedDBIx::Class::Relationship::Base::update_from_related
0000s0sDBIx::Class::Relationship::Base::::update_or_create_relatedDBIx::Class::Relationship::Base::update_or_create_related
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1package DBIx::Class::Relationship::Base;
2
3238µs230µs
# spent 22µs (14+8) within DBIx::Class::Relationship::Base::BEGIN@3 which was called: # once (14µs+8µs) by Class::C3::Componentised::ensure_class_loaded at line 3
use strict;
# spent 22µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@3 # spent 8µs making 1 call to strict::import
4240µs224µs
# spent 18µs (13+6) within DBIx::Class::Relationship::Base::BEGIN@4 which was called: # once (13µs+6µs) by Class::C3::Componentised::ensure_class_loaded at line 4
use warnings;
# spent 18µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@4 # spent 6µs making 1 call to warnings::import
5
6273µs250µs
# spent 50µs (10+40) within DBIx::Class::Relationship::Base::BEGIN@6 which was called: # once (10µs+40µs) by Class::C3::Componentised::ensure_class_loaded at line 6
use base qw/DBIx::Class/;
# spent 50µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@6 # spent 40µs making 1 call to base::import, recursion: max depth 1, sum of overlapping time 40µs
7
8255µs261µs
# spent 36µs (10+25) within DBIx::Class::Relationship::Base::BEGIN@8 which was called: # once (10µs+25µs) by Class::C3::Componentised::ensure_class_loaded at line 8
use Scalar::Util qw/weaken blessed/;
# spent 36µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@8 # spent 25µs making 1 call to Exporter::import
9258µs260µs
# spent 37µs (14+23) within DBIx::Class::Relationship::Base::BEGIN@9 which was called: # once (14µs+23µs) by Class::C3::Componentised::ensure_class_loaded at line 9
use Try::Tiny;
# spent 37µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@9 # spent 23µs making 1 call to Exporter::import
10239µs235µs
# spent 22µs (8+14) within DBIx::Class::Relationship::Base::BEGIN@10 which was called: # once (8µs+14µs) by Class::C3::Componentised::ensure_class_loaded at line 10
use DBIx::Class::_Util 'UNRESOLVABLE_CONDITION';
# spent 22µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@10 # spent 14µs making 1 call to Exporter::import
1121.96ms2273µs
# spent 140µs (8+132) within DBIx::Class::Relationship::Base::BEGIN@11 which was called: # once (8µs+132µs) by Class::C3::Componentised::ensure_class_loaded at line 11
use namespace::clean;
# spent 140µs making 1 call to DBIx::Class::Relationship::Base::BEGIN@11 # spent 132µs making 1 call to namespace::clean::import
12
13=head1 NAME
14
15DBIx::Class::Relationship::Base - Inter-table relationships
16
17=head1 SYNOPSIS
18
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 );
29
30=head1 DESCRIPTION
31
32This class provides methods to describe the relationships between the
33tables in your database model. These are the "bare bones" relationships
34methods, for predefined ones, look in L<DBIx::Class::Relationship>.
35
36=head1 METHODS
37
38=head2 add_relationship
39
40=over 4
41
42=item Arguments: $rel_name, $foreign_class, $condition, $attrs
43
44=back
45
46 __PACKAGE__->add_relationship('rel_name',
47 'Foreign::Class',
48 $condition, $attrs);
49
50Create a custom relationship between one result source and another
51source, indicated by its class name.
52
53=head3 condition
54
55The condition argument describes the C<ON> clause of the C<JOIN>
56expression used to connect the two sources when creating SQL queries.
57
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:
68
69 My::Schema::Author->has_many(
70 books => 'My::Schema::Book',
71 { 'foreign.author_id' => 'self.id' }
72 );
73
74A query like:
75
76 $author_rs->search_related('books')->next
77
78will result in the following C<JOIN> clause:
79
80 ... FROM author me LEFT JOIN book books ON books.author_id = me.id ...
81
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
86Similarly:
87
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
99
100will result in the C<JOIN> clause:
101
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 ...
106
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
110=head4 Multiple groups of simple equality conditions
111
112As is the default in L<SQL::Abstract>, the key-value pairs will be
113C<AND>ed in the resulting C<JOIN> clause. An C<OR> can be achieved with
114an arrayref. For example a condition like:
115
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 );
123
124will translate to the following C<JOIN> clause:
125
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 ...
129
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)
133
134=head4 Custom join conditions
135
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
142To specify joins which describe more than a simple equality of column
143values, the custom join condition coderef syntax can be used. For
144example:
145
146 My::Schema::Artist->has_many(
147 cds_80s => 'My::Schema::CD',
148 sub {
149 my $args = shift;
150
151 return {
152 "$args->{foreign_alias}.artist" => { -ident => "$args->{self_alias}.artistid" },
153 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
154 };
155 }
156 );
157
158 ...
159
160 $artist_rs->search_related('cds_80s')->next;
161
162will result in the C<JOIN> clause:
163
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 > ?
168
169with the bind values:
170
171 '1990', '1979'
172
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
184elect to additionally return a simplified B<optional> join-free condition
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:
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 },
219 ! $args->{self_result_object} ? () : {
220 "$args->{foreign_alias}.artist" => $args->{self_result_object}->artistid,
221 "$args->{foreign_alias}.year" => { '>', "1979", '<', "1990" },
222 },
223 ! $args->{foreign_values} ? () : {
224 "$args->{self_alias}.artistid" => $args->{foreign_values}{artist},
225 }
226 );
227 }
228
229Then this code:
230
231 my $artist = $schema->resultset("Artist")->find({ id => 4 });
232 $artist->cds_80s->all;
233
234Can skip a C<JOIN> altogether and instead produce:
235
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 > ?
241
242With the bind values:
243
244 '4', '1990', '1979'
245
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
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).
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}->({
267 self_resultsource => The resultsource instance on which rel_name is registered
268 rel_name => The relationship name (does *NOT* always match foreign_alias)
269
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)
272
273 # only one of these (or none at all) will ever be supplied to aid in the
274 # construction of a join-free condition
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 )
282
283 # deprecated inconsistent names, will be forever available for legacy code
284 self_rowobj => Old deprecated slot for self_result_object
285 foreign_relname => Old deprecated slot for rel_name
286 });
287
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:
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
309=item proxy =E<gt> $column | \@columns | \%column
310
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
317=over 4
318
319=item \@columns
320
321An arrayref containing a list of accessors in the foreign class to create in
322the main class. If, for example, you do the following:
323
324 MyApp::Schema::CD->might_have(liner_notes => 'MyApp::Schema::LinerNotes',
325 undef, {
326 proxy => [ qw/notes/ ],
327 });
328
329Then, assuming MyApp::Schema::LinerNotes has an accessor named notes, you can do:
330
331 my $cd = MyApp::Schema::CD->find(1);
332 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
333 # created if it doesn't exist
334
335For a 'belongs_to relationship, note the 'cascade_update':
336
337 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd,
338 { proxy => ['title'], cascade_update => 1 }
339 );
340 $track->title('New Title');
341 $track->update; # updates title in CD
342
343=item \%column
344
345A hashref where each key is the accessor you want installed in the main class,
346and its value is the name of the original in the foreign class.
347
348 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
349 proxy => { cd_title => 'title' },
350 });
351
352This will create an accessor named C<cd_title> on the C<$track> result object.
353
354=back
355
356NOTE: you can pass a nested struct too, for example:
357
358 MyApp::Schema::Track->belongs_to( cd => 'MyApp::Schema::CD', 'cd', {
359 proxy => [ 'year', { cd_title => 'title' } ],
360 });
361
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
371=item is_foreign_key_constraint
372
373If you are using L<SQL::Translator> to create SQL for you and you find that it
374is creating constraints where it shouldn't, or not creating them where it
375should, set this attribute to a true or false value to override the detection
376of when to create constraints.
377
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
382be copied too. To turn this behaviour off, pass C<< cascade_copy => 0 >>
383in the C<$attr> hashref.
384
385The behaviour defaults to C<< cascade_copy => 1 >> for C<has_many>
386relationships.
387
388=item cascade_delete
389
390By default, DBIx::Class cascades deletes across C<has_many>,
391C<has_one> and C<might_have> relationships. You can disable this
392behaviour on a per-relationship basis by supplying
393C<< cascade_delete => 0 >> in the relationship attributes.
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
402By default, DBIx::Class cascades updates across C<has_one> and
403C<might_have> relationships. You can disable this behaviour on a
404per-relationship basis by supplying C<< cascade_update => 0 >> in
405the relationship attributes.
406
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
409use 'update' on it, you must set C<< cascade_update => 1 >>.
410
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.
415
416=item on_delete / on_update
417
418If you are using L<SQL::Translator> to create SQL for you, you can use these
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
421interrogating the attributes of the B<opposite> relationship. For any 'multi'
422relationship with C<< cascade_delete => 1 >>, the corresponding belongs_to
423relationship will be created with an C<ON DELETE CASCADE> constraint. For any
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
426use the RDBMS' default constraint type, pass C<< on_delete => undef >> or
427C<< on_delete => '' >>, and the same for C<on_update> respectively.
428
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
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
442=back
443
444=head2 register_relationship
445
446=over 4
447
448=item Arguments: $rel_name, $rel_info
449
450=back
451
452Registers a relationship on the class. This is called internally by
453DBIx::Class::ResultSourceProxy to set up Accessors and Proxies.
454
455=cut
456
45731979µssub register_relationship { }
458
459=head2 related_resultset
460
461=over 4
462
463=item Arguments: $rel_name
464
465=item Return Value: L<$related_resultset|DBIx::Class::ResultSet>
466
467=back
468
469 $rs = $cd->related_resultset('artist');
470
471Returns a L<DBIx::Class::ResultSet> for the relationship named
472$rel_name.
473
474=head2 $relationship_accessor
475
476=over 4
477
478=item Arguments: none
479
480=item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | L<$related_resultset|DBIx::Class::ResultSet> | undef
481
482=back
483
484 # These pairs do the same thing
485 $result = $cd->related_resultset('artist')->single; # has_one relationship
486 $result = $cd->artist;
487 $rs = $cd->related_resultset('tracks'); # has_many relationship
488 $rs = $cd->tracks;
489
490This is the recommended way to traverse through relationships, based
491on the L</accessor> name given in the relationship definition.
492
493This will return either a L<Result|DBIx::Class::Manual::ResultClass> or a
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
499=cut
500
501sub related_resultset {
502 my $self = shift;
503
504 $self->throw_exception("Can't call *_related as class methods")
505 unless ref $self;
506
507 my $rel = shift;
508
509 return $self->{related_resultsets}{$rel}
510 if defined $self->{related_resultsets}{$rel};
511
512 return $self->{related_resultsets}{$rel} = do {
513
514 my $rsrc = $self->result_source;
515
516 my $rel_info = $rsrc->relationship_info($rel)
517 or $self->throw_exception( "No such relationship '$rel'" );
518
519 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
520 $attrs = { %{$rel_info->{attrs} || {}}, %$attrs };
521
522 $self->throw_exception( "Invalid query: @_" )
523 if (@_ > 1 && (@_ % 2 == 1));
524 my $query = ((@_ > 1) ? {@_} : shift);
525
526 # condition resolution may fail if an incomplete master-object prefetch
527 # is encountered - that is ok during prefetch construction (not yet in_storage)
528 my ($cond, $is_crosstable) = try {
529 $rsrc->_resolve_condition( $rel_info->{cond}, $rel, $self, $rel )
530 }
531 catch {
532 $self->throw_exception ($_) if $self->in_storage;
533 UNRESOLVABLE_CONDITION; # RV, no return()
534 };
535
536 # keep in mind that the following if() block is part of a do{} - no return()s!!!
537 if ($is_crosstable and ref $rel_info->{cond} eq 'CODE') {
538
539 # A WHOREIFFIC hack to reinvoke the entire condition resolution
540 # with the correct alias. Another way of doing this involves a
541 # lot of state passing around, and the @_ positions are already
542 # mapped out, making this crap a less icky option.
543 #
544 # The point of this exercise is to retain the spirit of the original
545 # $obj->search_related($rel) where the resulting rset will have the
546 # root alias as 'me', instead of $rel (as opposed to invoking
547 # $rs->search_related)
548
549 # make the fake 'me' rel
550 local $rsrc->{_relationships}{me} = {
551 %{ $rsrc->{_relationships}{$rel} },
552 _original_name => $rel,
553 };
554
555 my $obj_table_alias = lc($rsrc->source_name) . '__row';
556 $obj_table_alias =~ s/\W+/_/g;
557
558 $rsrc->resultset->search(
559 $self->ident_condition($obj_table_alias),
560 { alias => $obj_table_alias },
561 )->search_related('me', $query, $attrs)
562 }
563 else {
564 # FIXME - this conditional doesn't seem correct - got to figure out
565 # at some point what it does. Also the entire UNRESOLVABLE_CONDITION
566 # business seems shady - we could simply not query *at all*
567 if ($cond eq UNRESOLVABLE_CONDITION) {
568 my $reverse = $rsrc->reverse_relationship_info($rel);
569 foreach my $rev_rel (keys %$reverse) {
570 if ($reverse->{$rev_rel}{attrs}{accessor} && $reverse->{$rev_rel}{attrs}{accessor} eq 'multi') {
571 weaken($attrs->{related_objects}{$rev_rel}[0] = $self);
572 } else {
573 weaken($attrs->{related_objects}{$rev_rel} = $self);
574 }
575 }
576 }
577 elsif (ref $cond eq 'ARRAY') {
578 $cond = [ map {
579 if (ref $_ eq 'HASH') {
580 my $hash;
581 foreach my $key (keys %$_) {
582 my $newkey = $key !~ /\./ ? "me.$key" : $key;
583 $hash->{$newkey} = $_->{$key};
584 }
585 $hash;
586 } else {
587 $_;
588 }
589 } @$cond ];
590 }
591 elsif (ref $cond eq 'HASH') {
592 foreach my $key (grep { ! /\./ } keys %$cond) {
593 $cond->{"me.$key"} = delete $cond->{$key};
594 }
595 }
596
597 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
598 $rsrc->related_source($rel)->resultset->search(
599 $query, $attrs
600 );
601 }
602 };
603}
604
605=head2 search_related
606
607=over 4
608
609=item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
610
611=item Return Value: L<$resultset|DBIx::Class::ResultSet> (scalar context) | L<@result_objs|DBIx::Class::Manual::ResultClass> (list context)
612
613=back
614
615Run a search on a related resultset. The search will be restricted to the
616results represented by the L<DBIx::Class::ResultSet> it was called
617upon.
618
619See L<DBIx::Class::ResultSet/search_related> for more information.
620
621=cut
622
623sub search_related {
624 return shift->related_resultset(shift)->search(@_);
625}
626
627=head2 search_related_rs
628
629This method works exactly the same as search_related, except that
630it guarantees a resultset, even in list context.
631
632=cut
633
634sub search_related_rs {
635 return shift->related_resultset(shift)->search_rs(@_);
636}
637
638=head2 count_related
639
640=over 4
641
642=item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
643
644=item Return Value: $count
645
646=back
647
648Returns the count of all the rows in the related resultset, restricted by the
649current result or where conditions.
650
651=cut
652
653sub count_related {
654 shift->search_related(@_)->count;
655}
656
657=head2 new_related
658
659=over 4
660
661=item Arguments: $rel_name, \%col_data
662
663=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
664
665=back
666
667Create a new result object of the related foreign class. It will magically set
668any foreign key columns of the new object to the related primary key columns
669of the source object for you. The newly created result will not be saved into
670your storage until you call L<DBIx::Class::Row/insert> on it.
671
672=cut
673
674sub new_related {
675 my ($self, $rel, $data) = @_;
676
677 return $self->search_related($rel)->new_result( $self->result_source->_resolve_relationship_condition (
678 infer_values_based_on => $data,
679 rel_name => $rel,
680 self_result_object => $self,
681 foreign_alias => $rel,
682 self_alias => 'me',
683 )->{inferred_values} );
684}
685
686=head2 create_related
687
688=over 4
689
690=item Arguments: $rel_name, \%col_data
691
692=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
693
694=back
695
696 my $result = $obj->create_related($rel_name, \%col_data);
697
698Creates a new result object, similarly to new_related, and also inserts the
699result's data into your storage medium. See the distinction between C<create>
700and C<new> in L<DBIx::Class::ResultSet> for details.
701
702=cut
703
704sub create_related {
705 my $self = shift;
706 my $rel = shift;
707 my $obj = $self->new_related($rel, @_)->insert;
708 delete $self->{related_resultsets}->{$rel};
709 return $obj;
710}
711
712=head2 find_related
713
714=over 4
715
716=item Arguments: $rel_name, \%col_data | @pk_values, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
717
718=item Return Value: L<$result|DBIx::Class::Manual::ResultClass> | undef
719
720=back
721
722 my $result = $obj->find_related($rel_name, \%col_data);
723
724Attempt to find a related object using its primary key or unique constraints.
725See L<DBIx::Class::ResultSet/find> for details.
726
727=cut
728
729sub find_related {
730 #my ($self, $rel, @args) = @_;
731 return shift->search_related(shift)->find(@_);
732}
733
734=head2 find_or_new_related
735
736=over 4
737
738=item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
739
740=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
741
742=back
743
744Find a result object of a related class. See L<DBIx::Class::ResultSet/find_or_new>
745for details.
746
747=cut
748
749sub find_or_new_related {
750 my $self = shift;
751 my $obj = $self->find_related(@_);
752 return defined $obj ? $obj : $self->new_related(@_);
753}
754
755=head2 find_or_create_related
756
757=over 4
758
759=item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
760
761=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
762
763=back
764
765Find or create a result object of a related class. See
766L<DBIx::Class::ResultSet/find_or_create> for details.
767
768=cut
769
770sub find_or_create_related {
771 my $self = shift;
772 my $obj = $self->find_related(@_);
773 return (defined($obj) ? $obj : $self->create_related(@_));
774}
775
776=head2 update_or_create_related
777
778=over 4
779
780=item Arguments: $rel_name, \%col_data, { key => $unique_constraint, L<%attrs|DBIx::Class::ResultSet/ATTRIBUTES> }?
781
782=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
783
784=back
785
786Update or create a result object of a related class. See
787L<DBIx::Class::ResultSet/update_or_create> for details.
788
789=cut
790
791sub update_or_create_related {
792 #my ($self, $rel, @args) = @_;
793 shift->related_resultset(shift)->update_or_create(@_);
794}
795
796=head2 set_from_related
797
798=over 4
799
800=item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
801
802=item Return Value: not defined
803
804=back
805
806 $book->set_from_related('author', $author_obj);
807 $book->author($author_obj); ## same thing
808
809Set column values on the current object, using related values from the given
810related object. This is used to associate previously separate objects, for
811example, to set the correct author for a book, find the Author object, then
812call set_from_related on the book.
813
814This is called internally when you pass existing objects as values to
815L<DBIx::Class::ResultSet/create>, or pass an object to a belongs_to accessor.
816
817The columns are only set in the local copy of the object, call
818L<update|DBIx::Class::Row/update> to update them in the storage.
819
820=cut
821
822sub set_from_related {
823 my ($self, $rel, $f_obj) = @_;
824
825 $self->set_columns( $self->result_source->_resolve_relationship_condition (
826 infer_values_based_on => {},
827 rel_name => $rel,
828 foreign_values => $f_obj,
829 foreign_alias => $rel,
830 self_alias => 'me',
831 )->{inferred_values} );
832
833 return 1;
834}
835
836=head2 update_from_related
837
838=over 4
839
840=item Arguments: $rel_name, L<$result|DBIx::Class::Manual::ResultClass>
841
842=item Return Value: not defined
843
844=back
845
846 $book->update_from_related('author', $author_obj);
847
848The same as L</"set_from_related">, but the changes are immediately updated
849in storage.
850
851=cut
852
853sub update_from_related {
854 my $self = shift;
855 $self->set_from_related(@_);
856 $self->update;
857}
858
859=head2 delete_related
860
861=over 4
862
863=item Arguments: $rel_name, $cond?, L<\%attrs?|DBIx::Class::ResultSet/ATTRIBUTES>
864
865=item Return Value: $underlying_storage_rv
866
867=back
868
869Delete any related row, subject to the given conditions. Internally, this
870calls:
871
872 $self->search_related(@_)->delete
873
874And returns the result of that.
875
876=cut
877
878sub delete_related {
879 my $self = shift;
880 my $obj = $self->search_related(@_)->delete;
881 delete $self->{related_resultsets}->{$_[0]};
882 return $obj;
883}
884
885=head2 add_to_$rel
886
887B<Currently only available for C<has_many>, C<many_to_many> and 'multi' type
888relationships.>
889
890=head3 has_many / multi
891
892=over 4
893
894=item Arguments: \%col_data
895
896=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
897
898=back
899
900Creates/inserts a new result object. Internally, this calls:
901
902 $self->create_related($rel, @_)
903
904And returns the result of that.
905
906=head3 many_to_many
907
908=over 4
909
910=item Arguments: (\%col_data | L<$result|DBIx::Class::Manual::ResultClass>), \%link_col_data?
911
912=item Return Value: L<$result|DBIx::Class::Manual::ResultClass>
913
914=back
915
916 my $role = $schema->resultset('Role')->find(1);
917 $actor->add_to_roles($role);
918 # creates a My::DBIC::Schema::ActorRoles linking table result object
919
920 $actor->add_to_roles({ name => 'lead' }, { salary => 15_000_000 });
921 # creates a new My::DBIC::Schema::Role result object and the linking table
922 # object with an extra column in the link
923
924Adds a linking table object. If the first argument is a hash reference, the
925related object is created first with the column values in the hash. If an object
926reference is given, just the linking table object is created. In either case,
927any additional column values for the linking table object can be specified in
928C<\%link_col_data>.
929
930See L<DBIx::Class::Relationship/many_to_many> for additional details.
931
932=head2 set_$rel
933
934B<Currently only available for C<many_to_many> relationships.>
935
936=over 4
937
938=item Arguments: (\@hashrefs_of_col_data | L<\@result_objs|DBIx::Class::Manual::ResultClass>), $link_vals?
939
940=item Return Value: not defined
941
942=back
943
944 my $actor = $schema->resultset('Actor')->find(1);
945 my @roles = $schema->resultset('Role')->search({ role =>
946 { '-in' => ['Fred', 'Barney'] } } );
947
948 $actor->set_roles(\@roles);
949 # Replaces all of $actor's previous roles with the two named
950
951 $actor->set_roles(\@roles, { salary => 15_000_000 });
952 # Sets a column in the link table for all roles
953
954
955Replace all the related objects with the given reference to a list of
956objects. This does a C<delete> B<on the link table resultset> to remove the
957association between the current object and all related objects, then calls
958C<add_to_$rel> repeatedly to link all the new objects.
959
960Note that this means that this method will B<not> delete any objects in the
961table on the right side of the relation, merely that it will delete the link
962between them.
963
964Due to a mistake in the original implementation of this method, it will also
965accept a list of objects or hash references. This is B<deprecated> and will be
966removed in a future version.
967
968=head2 remove_from_$rel
969
970B<Currently only available for C<many_to_many> relationships.>
971
972=over 4
973
974=item Arguments: L<$result|DBIx::Class::Manual::ResultClass>
975
976=item Return Value: not defined
977
978=back
979
980 my $role = $schema->resultset('Role')->find(1);
981 $actor->remove_from_roles($role);
982 # removes $role's My::DBIC::Schema::ActorRoles linking table result object
983
984Removes the link between the current object and the related object. Note that
985the related object itself won't be deleted unless you call ->delete() on
986it. This method just removes the link between the two objects.
987
988=head1 FURTHER QUESTIONS?
989
990Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
991
992=head1 COPYRIGHT AND LICENSE
993
994This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
995by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
996redistribute it and/or modify it under the same terms as the
997L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
998
999=cut
1000
100113µs1213µs1;
# spent 213µs making 1 call to B::Hooks::EndOfScope::XS::__ANON__