1 package DBIx::Class::Relationship::Base;
6 use base qw/DBIx::Class/;
8 __PACKAGE__->mk_classdata('_relationships', { } );
12 DBIx::Class::Relationship::Base - Inter-table relationships
18 This class provides methods to describe the relationships between the
19 tables in your database model. These are the "bare bones" relationships
20 methods, for predefined ones, look in L<DBIx::Class::Relationship>.
24 =head2 add_relationship
26 =head3 Arguments: ('relname', 'Foreign::Class', $cond, $attrs)
28 __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
30 The condition needs to be an SQL::Abstract-style representation of the
31 join between the tables. When resolving the condition for use in a JOIN,
32 keys using the psuedo-table I<foreign> are resolved to mean "the Table on the
33 other side of the relationship", and values using the psuedo-table I<self>
34 are resolved to mean "the Table this class is representing". Other
35 restrictions, such as by value, sub-select and other tables, may also be
36 used. Please check your database for JOIN parameter support.
38 For example, if you're creating a rel from Author to Book, where the Book
39 table has a column author_id containing the ID of the Author row:
41 { 'foreign.author_id' => 'self.id' }
43 will result in the JOIN clause
45 author me JOIN book book ON bar.author_id = me.id
47 You can specify as many foreign => self mappings as necessary. Each key/value
48 pair provided in a hashref will be used as ANDed conditions, to add an ORed
49 condition, use an arrayref of hashrefs. See the L<SQL::Abstract> documentation
52 Valid attributes are as follows:
58 Explicitly specifies the type of join to use in the relationship. Any SQL
59 join type is valid, e.g. C<LEFT> or C<RIGHT>. It will be placed in the SQL
60 command immediately before C<JOIN>.
64 An arrayref containing a list of accessors in the foreign class to create in
65 the main class. If, for example, you do the following:
67 MyDB::Schema::CD->might_have(liner_notes => 'MyDB::Schema::LinerNotes', undef, {
68 proxy => [ qw/notes/ ],
71 Then, assuming MyDB::Schema::LinerNotes has an accessor named notes, you can do:
73 my $cd = MyDB::Schema::CD->find(1);
74 $cd->notes('Notes go here'); # set notes -- LinerNotes object is
75 # created if it doesn't exist
79 Specifies the type of accessor that should be created for the relationship.
80 Valid values are C<single> (for when there is only a single related object),
81 C<multi> (when there can be many), and C<filter> (for when there is a single
82 related object, but you also want the relationship accessor to double as
83 a column accessor). For C<multi> accessors, an add_to_* method is also
84 created, which calls C<create_related> for the relationship.
88 =head2 register_relationship
90 =head3 Arguments: ($relname, $rel_info)
92 Registers a relationship on the class. This is called internally by
93 L<DBIx::Class::ResultSourceProxy> to set up Accessors and Proxies.
97 sub register_relationship { }
99 =head2 related_resultset($name)
101 $rs = $obj->related_resultset('related_table');
103 Returns a L<DBIx::Class::ResultSet> for the relationship named $name.
107 sub related_resultset {
109 $self->throw_exception("Can't call *_related as class methods") unless ref $self;
111 my $rel_obj = $self->relationship_info($rel);
112 $self->throw_exception( "No such relationship ${rel}" ) unless $rel_obj;
114 return $self->{related_resultsets}{$rel} ||= do {
115 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
116 $attrs = { %{$rel_obj->{attrs} || {}}, %$attrs };
118 $self->throw_exception( "Invalid query: @_" ) if (@_ > 1 && (@_ % 2 == 1));
119 my $query = ((@_ > 1) ? {@_} : shift);
121 my $cond = $self->result_source->resolve_condition($rel_obj->{cond}, $rel, $self);
122 if (ref $cond eq 'ARRAY') {
123 $cond = [ map { my $hash;
124 foreach my $key (keys %$_) {
125 my $newkey = $key =~ /\./ ? "me.$key" : $key;
126 $hash->{$newkey} = $_->{$key};
129 foreach my $key (grep { ! /\./ } keys %$cond) {
130 $cond->{"me.$key"} = delete $cond->{$key};
133 $query = ($query ? { '-and' => [ $cond, $query ] } : $cond);
134 $self->result_source->related_source($rel)->resultset->search($query, $attrs);
138 =head2 search_related
140 $rs->search_related('relname', $cond, $attrs);
142 Run a search on a related resultset. The search will be restricted to the
143 item or items represented by the L<DBIx::Class::ResultSet> it was called
144 upon. This method can be called on a ResultSet, a Row or a ResultSource class.
149 return shift->related_resultset(shift)->search(@_);
154 $obj->count_related('relname', $cond, $attrs);
156 Returns the count of all the items in the related resultset, restricted by
157 the current item or where conditions. Can be called on a L<DBIx::Classl::Manual::Glossary/"ResultSet"> or a L<DBIx::Class::Manual::Glossary/"Row"> object.
163 return $self->search_related(@_)->count;
168 my $new_obj = $obj->new_related('relname', \%col_data);
170 Create a new item of the related foreign class. If called on a
171 L<DBIx::Class::Manual::Glossary/"Row"> object, it will magically
172 set any primary key values into foreign key columns for you. The newly
173 created item will not be saved into your storage until you call C<insert>
179 my ($self, $rel, $values, $attrs) = @_;
180 return $self->search_related($rel)->new($values, $attrs);
183 =head2 create_related
185 my $new_obj = $obj->create_related('relname', \%col_data);
187 Creates a new item, similarly to new_related, and also inserts the item's data
188 into your storage medium. See the distinction between C<create> and C<new>
189 in L<DBIx::Class::ResultSet> for details.
196 my $obj = $self->search_related($rel)->create(@_);
197 delete $self->{related_resultsets}->{$rel};
203 my $found_item = $obj->find_related('relname', @pri_vals | \%pri_vals);
205 Attempt to find a related object using its primary key or unique constraints.
206 See C<find> in L<DBIx::Class::ResultSet> for details.
213 return $self->search_related($rel)->find(@_);
216 =head2 find_or_create_related
218 my $new_obj = $obj->find_or_create_related('relname', \%col_data);
220 Find or create an item of a related class. See C<find_or_create> in
221 L<DBIx::Class::ResultSet> for details.
225 sub find_or_create_related {
227 return $self->find_related(@_) || $self->create_related(@_);
230 =head2 set_from_related
232 $book->set_from_related('author', $author_obj);
234 Set column values on the current object, using related values from the given
235 related object. This is used to associate previously separate objects, for
236 example, to set the correct author for a book, find the Author object, then
237 call set_from_related on the book.
239 The columns are only set in the local copy of the object, call C<update> to set
244 sub set_from_related {
245 my ($self, $rel, $f_obj) = @_;
246 my $rel_obj = $self->relationship_info($rel);
247 $self->throw_exception( "No such relationship ${rel}" ) unless $rel_obj;
248 my $cond = $rel_obj->{cond};
249 $self->throw_exception( "set_from_related can only handle a hash condition; the "
250 ."condition for $rel is of type ".(ref $cond ? ref $cond : 'plain scalar'))
251 unless ref $cond eq 'HASH';
252 my $f_class = $self->result_source->schema->class($rel_obj->{class});
253 $self->throw_exception( "Object $f_obj isn't a ".$f_class )
254 unless $f_obj->isa($f_class);
256 $self->result_source->resolve_condition(
257 $rel_obj->{cond}, $f_obj, $rel));
261 =head2 update_from_related
263 $book->update_from_related('author', $author_obj);
265 As C<set_from_related>, but the changes are immediately updated onto your
270 sub update_from_related {
272 $self->set_from_related(@_);
276 =head2 delete_related
278 $obj->delete_related('relname', $cond, $attrs);
280 Delete any related item subject to the given conditions.
286 my $obj = $self->search_related(@_)->delete;
287 delete $self->{related_resultsets}->{$_[0]};
295 Matt S. Trout <mst@shadowcatsystems.co.uk>
299 You may distribute this code under the same terms as Perl itself.