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