1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
10 DBIx::Class::Relationship::Base - Inter-table relationships
16 This class provides methods to describe the relationships between the
17 tables in your database model. These are the "bare bones" relationships
18 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
22 =head2 add_relationship
26 =item Arguments: ('relname', 'Foreign::Class', $cond, $attrs)
30 __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
32 The condition needs to be an SQL::Abstract-style representation of the
33 join between the tables. When resolving the condition for use in a JOIN,
34 keys using the pseudo-table I<foreign> are resolved to mean "the Table on the
35 other side of the relationship", and values using the pseudo-table I<self>
36 are resolved to mean "the Table this class is representing". Other
37 restrictions, such as by value, sub-select and other tables, may also be
38 used. Please check your database for JOIN parameter support.
40 For example, if you're creating a rel from Author to Book, where the Book
41 table has a column author_id containing the ID of the Author row:
43 { 'foreign.author_id' => 'self.id' }
45 will result in the JOIN clause
47 author me JOIN book book ON bar.author_id = me.id
49 You can specify as many foreign => self mappings as necessary. Each key/value
50 pair provided in a hashref will be used as ANDed conditions, to add an ORed
51 condition, use an arrayref of hashrefs. See the L<SQL::Abstract> documentation
54 Valid attributes are as follows:
60 Explicitly specifies the type of join to use in the relationship. Any SQL
61 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
62 command immediately before C<JOIN>.
66 An arrayref containing a list of accessors in the foreign class to create in
67 the main class. If, for example, you do the following:
69 MyDB::Schema::CD->might_have(liner_notes => 'MyDB::Schema::LinerNotes',
71 proxy => [ qw/notes/ ],
74 Then, assuming MyDB::Schema::LinerNotes has an accessor named notes, you can do:
76 my $cd = MyDB::Schema::CD->find(1);
77 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
78 # created if it doesn't exist
82 Specifies the type of accessor that should be created for the relationship.
83 Valid values are C<single> (for when there is only a single related object),
84 C<multi> (when there can be many), and C<filter> (for when there is a single
85 related object, but you also want the relationship accessor to double as
86 a column accessor). For C<multi> accessors, an add_to_* method is also
87 created, which calls C<create_related> for the relationship.
91 =head2 register_relationship
95 =item Arguments: ($relname, $rel_info)
99 Registers a relationship on the class. This is called internally by
100 L<DBIx::Class::ResultSourceProxy> to set up Accessors and Proxies.
104 sub register_relationship { }
106 =head2 related_resultset
110 =item Arguments: ($relationship_name)
112 =item Returns: $related_resultset
116 $rs = $cd->related_resultset('artist');
118 Returns a L<DBIx::Class::ResultSet> for the relationship named
123 sub related_resultset {
125 $self->throw_exception("Can't call *_related as class methods")
128 my $rel_obj = $self->relationship_info($rel);
129 $self->throw_exception( "No such relationship ${rel}" )
132 return $self->{related_resultsets}{$rel} ||= do {
133 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
134 $attrs = { %{$rel_obj->{attrs} || {}}, %$attrs };
136 $self->throw_exception( "Invalid query: @_" )
137 if (@_ > 1 && (@_ % 2 == 1));
138 my $query = ((@_ > 1) ? {@_} : shift);
140 my $cond = $self->result_source->resolve_condition(
141 $rel_obj->{cond}, $rel, $self
143 if (ref $cond eq 'ARRAY') {
144 $cond = [ map { my $hash;
145 foreach my $key (keys %$_) {
146 my $newkey = $key =~ /\./ ? "me.$key" : $key;
147 $hash->{$newkey} = $_->{$key};
150 foreach my $key (grep { ! /\./ } keys %$cond) {
151 $cond->{"me.$key"} = delete $cond->{$key};
154 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
155 $self->result_source->related_source($rel)->resultset->search(
161 =head2 search_related
163 $rs->search_related('relname', $cond, $attrs);
165 Run a search on a related resultset. The search will be restricted to the
166 item or items represented by the L<DBIx::Class::ResultSet> it was called
167 upon. This method can be called on a ResultSet, a Row or a ResultSource class.
172 return shift->related_resultset(shift)->search(@_);
177 $obj->count_related('relname', $cond, $attrs);
179 Returns the count of all the items in the related resultset, restricted by the
180 current item or where conditions. Can be called on a
181 L<DBIx::Class::Manual::Glossary/"ResultSet"> or a
182 L<DBIx::Class::Manual::Glossary/"Row"> object.
188 return $self->search_related(@_)->count;
193 my $new_obj = $obj->new_related('relname', \%col_data);
195 Create a new item of the related foreign class. If called on a
196 L<DBIx::Class::Manual::Glossary/"Row"> object, it will magically set any
197 primary key values into foreign key columns for you. The newly created item
198 will not be saved into your storage until you call L<DBIx::Class::Row/insert>
204 my ($self, $rel, $values, $attrs) = @_;
205 return $self->search_related($rel)->new($values, $attrs);
208 =head2 create_related
210 my $new_obj = $obj->create_related('relname', \%col_data);
212 Creates a new item, similarly to new_related, and also inserts the item's data
213 into your storage medium. See the distinction between C<create> and C<new>
214 in L<DBIx::Class::ResultSet> for details.
221 my $obj = $self->search_related($rel)->create(@_);
222 delete $self->{related_resultsets}->{$rel};
228 my $found_item = $obj->find_related('relname', @pri_vals | \%pri_vals);
230 Attempt to find a related object using its primary key or unique constraints.
231 See L<DBIx::Class::ResultSet/find> for details.
238 return $self->search_related($rel)->find(@_);
241 =head2 find_or_create_related
243 my $new_obj = $obj->find_or_create_related('relname', \%col_data);
245 Find or create an item of a related class. See
246 L<DBIx::Class::ResultSet/"find_or_create"> for details.
250 sub find_or_create_related {
252 return $self->find_related(@_) || $self->create_related(@_);
255 =head2 set_from_related
257 $book->set_from_related('author', $author_obj);
259 Set column values on the current object, using related values from the given
260 related object. This is used to associate previously separate objects, for
261 example, to set the correct author for a book, find the Author object, then
262 call set_from_related on the book.
264 The columns are only set in the local copy of the object, call L</update> to
265 set them in the storage.
269 sub set_from_related {
270 my ($self, $rel, $f_obj) = @_;
271 my $rel_obj = $self->relationship_info($rel);
272 $self->throw_exception( "No such relationship ${rel}" ) unless $rel_obj;
273 my $cond = $rel_obj->{cond};
274 $self->throw_exception(
275 "set_from_related can only handle a hash condition; the ".
276 "condition for $rel is of type ".
277 (ref $cond ? ref $cond : 'plain scalar')
278 ) unless ref $cond eq 'HASH';
279 my $f_class = $self->result_source->schema->class($rel_obj->{class});
280 $self->throw_exception( "Object $f_obj isn't a ".$f_class )
281 unless $f_obj->isa($f_class);
283 $self->result_source->resolve_condition(
284 $rel_obj->{cond}, $f_obj, $rel));
288 =head2 update_from_related
290 $book->update_from_related('author', $author_obj);
292 The same as L</"set_from_related">, but the changes are immediately updated
297 sub update_from_related {
299 $self->set_from_related(@_);
303 =head2 delete_related
305 $obj->delete_related('relname', $cond, $attrs);
307 Delete any related item subject to the given conditions.
313 my $obj = $self->search_related(@_)->delete;
314 delete $self->{related_resultsets}->{$_[0]};
322 Matt S. Trout <mst@shadowcatsystems.co.uk>
326 You may distribute this code under the same terms as Perl itself.