1 package DBIx::Class::ResultSet;
11 use Scalar::Util qw/weaken/;
13 use base qw/DBIx::Class/;
14 __PACKAGE__->load_components(qw/AccessorGroup/);
15 __PACKAGE__->mk_group_accessors('simple' => qw/result_source result_class/);
19 DBIx::Class::ResultSet - Responsible for fetching and creating resultset.
23 my $rs = $schema->resultset('User')->search(registered => 1);
24 my @rows = $schema->resultset('CD')->search(year => 2005);
28 The resultset is also known as an iterator. It is responsible for handling
29 queries that may return an arbitrary number of rows, e.g. via L</search>
30 or a C<has_many> relationship.
32 In the examples below, the following table classes are used:
34 package MyApp::Schema::Artist;
35 use base qw/DBIx::Class/;
36 __PACKAGE__->load_components(qw/Core/);
37 __PACKAGE__->table('artist');
38 __PACKAGE__->add_columns(qw/artistid name/);
39 __PACKAGE__->set_primary_key('artistid');
40 __PACKAGE__->has_many(cds => 'MyApp::Schema::CD');
43 package MyApp::Schema::CD;
44 use base qw/DBIx::Class/;
45 __PACKAGE__->load_components(qw/Core/);
46 __PACKAGE__->table('cd');
47 __PACKAGE__->add_columns(qw/cdid artist title year/);
48 __PACKAGE__->set_primary_key('cdid');
49 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Artist');
58 =item Arguments: ($source, \%$attrs)
62 The resultset constructor. Takes a source object (usually a
63 L<DBIx::Class::ResultSourceProxy::Table>) and an attribute hash (see
64 L</ATTRIBUTES> below). Does not perform any queries -- these are
65 executed as needed by the other methods.
67 Generally you won't need to construct a resultset manually. You'll
68 automatically get one from e.g. a L</search> called in scalar context:
70 my $rs = $schema->resultset('CD')->search({ title => '100th Window' });
76 return $class->new_result(@_) if ref $class;
78 my ($source, $attrs) = @_;
80 $attrs = Storable::dclone($attrs || {}); # { %{ $attrs || {} } };
81 #use Data::Dumper; warn Dumper($attrs);
82 my $alias = ($attrs->{alias} ||= 'me');
84 $attrs->{columns} ||= delete $attrs->{cols} if $attrs->{cols};
85 delete $attrs->{as} if $attrs->{columns};
86 $attrs->{columns} ||= [ $source->columns ] unless $attrs->{select};
88 map { m/\./ ? $_ : "${alias}.$_" } @{delete $attrs->{columns}}
89 ] if $attrs->{columns};
91 map { m/^\Q$alias.\E(.+)$/ ? $1 : $_ } @{$attrs->{select}}
93 if (my $include = delete $attrs->{include_columns}) {
94 push(@{$attrs->{select}}, @$include);
95 push(@{$attrs->{as}}, map { m/([^.]+)$/; $1; } @$include);
97 #use Data::Dumper; warn Dumper(@{$attrs}{qw/select as/});
99 $attrs->{from} ||= [ { $alias => $source->from } ];
100 $attrs->{seen_join} ||= {};
102 if (my $join = delete $attrs->{join}) {
103 foreach my $j (ref $join eq 'ARRAY' ? @$join : ($join)) {
104 if (ref $j eq 'HASH') {
105 $seen{$_} = 1 foreach keys %$j;
110 push(@{$attrs->{from}}, $source->resolve_join(
111 $join, $attrs->{alias}, $attrs->{seen_join})
115 $attrs->{group_by} ||= $attrs->{select} if delete $attrs->{distinct};
116 $attrs->{order_by} = [ $attrs->{order_by} ] if
117 $attrs->{order_by} and !ref($attrs->{order_by});
118 $attrs->{order_by} ||= [];
120 my $collapse = $attrs->{collapse} || {};
121 if (my $prefetch = delete $attrs->{prefetch}) {
123 foreach my $p (ref $prefetch eq 'ARRAY' ? @$prefetch : ($prefetch)) {
124 if ( ref $p eq 'HASH' ) {
125 foreach my $key (keys %$p) {
126 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
130 push(@{$attrs->{from}}, $source->resolve_join($p, $attrs->{alias}))
133 my @prefetch = $source->resolve_prefetch(
134 $p, $attrs->{alias}, {}, \@pre_order, $collapse);
135 push(@{$attrs->{select}}, map { $_->[0] } @prefetch);
136 push(@{$attrs->{as}}, map { $_->[1] } @prefetch);
138 push(@{$attrs->{order_by}}, @pre_order);
140 $attrs->{collapse} = $collapse;
141 # use Data::Dumper; warn Dumper($collapse) if keys %{$collapse};
143 if ($attrs->{page}) {
144 $attrs->{rows} ||= 10;
145 $attrs->{offset} ||= 0;
146 $attrs->{offset} += ($attrs->{rows} * ($attrs->{page} - 1));
150 result_source => $source,
151 result_class => $attrs->{result_class} || $source->result_class,
152 cond => $attrs->{where},
153 from => $attrs->{from},
154 collapse => $collapse,
156 page => delete $attrs->{page},
166 =item Arguments: (\%cond?, \%attrs?)
168 =item Returns: $resultset (scalar context), @row_objs (list context)
172 my @cds = $cd_rs->search({ year => 2001 }); # "... WHERE year = 2001"
173 my $new_rs = $cd_rs->search({ year => 2005 });
175 If you need to pass in additional attributes but no additional condition,
176 call it as C<search(undef, \%attrs);>.
178 # "SELECT name, artistid FROM $artist_table"
179 my @all_artists = $schema->resultset('Artist')->search(undef, {
180 columns => [qw/name artistid/],
191 my $attrs = { %{$self->{attrs}} };
192 my $having = delete $attrs->{having};
193 $attrs = { %$attrs, %{ pop(@_) } } if @_ > 1 and ref $_[$#_] eq 'HASH';
196 ? ((@_ == 1 || ref $_[0] eq "HASH")
199 ? $self->throw_exception(
200 "Odd number of arguments to search")
203 if (defined $where) {
204 $attrs->{where} = (defined $attrs->{where}
206 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
207 $where, $attrs->{where} ] }
211 if (defined $having) {
212 $attrs->{having} = (defined $attrs->{having}
214 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
215 $having, $attrs->{having} ] }
219 $rs = (ref $self)->new($self->result_source, $attrs);
225 return (wantarray ? $rs->all : $rs);
228 =head2 search_literal
232 =item Arguments: ($literal_cond, @bind?)
234 =item Returns: $resultset (scalar context), @row_objs (list context)
238 my @cds = $cd_rs->search_literal('year = ? AND title = ?', qw/2001 Reload/);
239 my $newrs = $artist_rs->search_literal('name = ?', 'Metallica');
241 Pass a literal chunk of SQL to be added to the conditional part of the
247 my ($self, $cond, @vals) = @_;
248 my $attrs = (ref $vals[$#vals] eq 'HASH' ? { %{ pop(@vals) } } : {});
249 $attrs->{bind} = [ @{$self->{attrs}{bind}||[]}, @vals ];
250 return $self->search(\$cond, $attrs);
257 =item Arguments: (@colvalues) | (\%cols, \%attrs?)
259 =item Returns: $row_object
263 Finds a row based on its primary key or unique constraint. For example:
265 my $cd = $schema->resultset('CD')->find(5);
267 Also takes an optional C<key> attribute, to search by a specific key or unique
268 constraint. For example:
270 my $cd = $schema->resultset('CD')->find(
272 artist => 'Massive Attack',
273 title => 'Mezzanine',
275 { key => 'artist_title' }
278 See also L</find_or_create> and L</update_or_create>.
283 my ($self, @vals) = @_;
284 my $attrs = (@vals > 1 && ref $vals[$#vals] eq 'HASH' ? pop(@vals) : {});
286 my @cols = $self->result_source->primary_columns;
287 if (exists $attrs->{key}) {
288 my %uniq = $self->result_source->unique_constraints;
289 $self->throw_exception(
290 "Unknown key $attrs->{key} on '" . $self->result_source->name . "'"
291 ) unless exists $uniq{$attrs->{key}};
292 @cols = @{ $uniq{$attrs->{key}} };
294 #use Data::Dumper; warn Dumper($attrs, @vals, @cols);
295 $self->throw_exception(
296 "Can't find unless a primary key or unique constraint is defined"
300 if (ref $vals[0] eq 'HASH') {
301 $query = { %{$vals[0]} };
302 } elsif (@cols == @vals) {
304 @{$query}{@cols} = @vals;
308 foreach my $key (grep { ! m/\./ } keys %$query) {
309 $query->{"$self->{attrs}{alias}.$key"} = delete $query->{$key};
311 #warn Dumper($query);
314 my $rs = $self->search($query,$attrs);
315 return keys %{$rs->{collapse}} ? $rs->next : $rs->single;
317 return keys %{$self->{collapse}} ?
318 $self->search($query)->next :
319 $self->single($query);
323 =head2 search_related
327 =item Arguments: (\%cond?, \%attrs?)
329 =item Returns: $new_resultset
333 $new_rs = $cd_rs->search_related('artist', {
337 Search the specified relationship, optionally specify a condition and
338 attributes for matching records. See L</ATTRIBUTES> for more information.
343 return shift->related_resultset(shift)->search(@_);
350 =item Arguments: (none)
352 =item Returns: $cursor
356 Returns a storage-driven cursor to the given resultset. See
357 L<DBIx::Class::Cursor> for more information.
363 my $attrs = { %{$self->{attrs}} };
364 return $self->{cursor}
365 ||= $self->result_source->storage->select($self->{from}, $attrs->{select},
366 $attrs->{where},$attrs);
373 =item Arguments: (\%cond)
375 =item Returns: $row_object
379 my $cd = $schema->resultset('CD')->single({ year => 2001 });
381 Inflates the first result without creating a cursor.
386 my ($self, $where) = @_;
387 my $attrs = { %{$self->{attrs}} };
389 if (defined $attrs->{where}) {
392 [ map { ref $_ eq 'ARRAY' ? [ -or => $_ ] : $_ }
393 $where, delete $attrs->{where} ]
396 $attrs->{where} = $where;
399 my @data = $self->result_source->storage->select_single(
400 $self->{from}, $attrs->{select},
401 $attrs->{where},$attrs);
402 return (@data ? $self->_construct_object(@data) : ());
410 =item Arguments: (\%cond?, \%attrs?)
412 =item Returns: $resultset (scalar context), @row_objs (list context)
416 # WHERE title LIKE '%blue%'
417 $cd_rs = $rs->search_like({ title => '%blue%'});
419 Perform a search, but use C<LIKE> instead of C<=> as the condition. Note
420 that this is simply a convenience method. You most likely want to use
421 L</search> with specific operators.
423 For more information, see L<DBIx::Class::Manual::Cookbook>.
429 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
430 my $query = ref $_[0] eq 'HASH' ? { %{shift()} }: {@_};
431 $query->{$_} = { 'like' => $query->{$_} } for keys %$query;
432 return $class->search($query, { %$attrs });
439 =item Arguments: ($first, $last)
441 =item Returns: $resultset (scalar context), @row_objs (list context)
445 Returns a subset of elements from the resultset.
450 my ($self, $min, $max) = @_;
451 my $attrs = { %{ $self->{attrs} || {} } };
452 $attrs->{offset} ||= 0;
453 $attrs->{offset} += $min;
454 $attrs->{rows} = ($max ? ($max - $min + 1) : 1);
455 my $slice = (ref $self)->new($self->result_source, $attrs);
456 return (wantarray ? $slice->all : $slice);
461 Returns the next element in the resultset (C<undef> is there is none).
463 Can be used to efficiently iterate over records in the resultset:
465 my $rs = $schema->resultset('CD')->search;
466 while (my $cd = $rs->next) {
474 if (@{$self->{all_cache} || []}) {
475 $self->{all_cache_position} ||= 0;
476 return $self->{all_cache}->[$self->{all_cache_position}++];
478 if ($self->{attrs}{cache}) {
479 $self->{all_cache_position} = 1;
480 return ($self->all)[0];
482 my @row = (exists $self->{stashed_row} ?
483 @{delete $self->{stashed_row}} :
486 # warn Dumper(\@row); use Data::Dumper;
487 return unless (@row);
488 return $self->_construct_object(@row);
491 sub _construct_object {
492 my ($self, @row) = @_;
493 my @as = @{ $self->{attrs}{as} };
495 my $info = $self->_collapse_result(\@as, \@row);
497 my $new = $self->result_class->inflate_result($self->result_source, @$info);
499 $new = $self->{attrs}{record_filter}->($new)
500 if exists $self->{attrs}{record_filter};
504 sub _collapse_result {
505 my ($self, $as, $row, $prefix) = @_;
510 foreach my $this_as (@$as) {
511 my $val = shift @copy;
512 if (defined $prefix) {
513 if ($this_as =~ m/^\Q${prefix}.\E(.+)$/) {
515 $remain =~ /^(?:(.*)\.)?([^.]+)$/;
516 $const{$1||''}{$2} = $val;
519 $this_as =~ /^(?:(.*)\.)?([^.]+)$/;
520 $const{$1||''}{$2} = $val;
524 my $info = [ {}, {} ];
525 foreach my $key (keys %const) {
528 my @parts = split(/\./, $key);
529 foreach my $p (@parts) {
530 $target = $target->[1]->{$p} ||= [];
532 $target->[0] = $const{$key};
534 $info->[0] = $const{$key};
539 if (defined $prefix) {
541 m/^\Q${prefix}.\E(.+)$/ ? ($1) : ()
542 } keys %{$self->{collapse}}
544 @collapse = keys %{$self->{collapse}};
548 my ($c) = sort { length $a <=> length $b } @collapse;
550 foreach my $p (split(/\./, $c)) {
551 $target = $target->[1]->{$p} ||= [];
553 my $c_prefix = (defined($prefix) ? "${prefix}.${c}" : $c);
554 my @co_key = @{$self->{collapse}{$c_prefix}};
555 my %co_check = map { ($_, $target->[0]->{$_}); } @co_key;
556 my $tree = $self->_collapse_result($as, $row, $c_prefix);
559 !defined($tree->[0]->{$_}) ||
560 $co_check{$_} ne $tree->[0]->{$_}
563 last unless (@raw = $self->cursor->next);
564 $row = $self->{stashed_row} = \@raw;
565 $tree = $self->_collapse_result($as, $row, $c_prefix);
566 #warn Data::Dumper::Dumper($tree, $row);
576 Returns a reference to the result source for this recordset.
583 Performs an SQL C<COUNT> with the same query as the resultset was built
584 with to find the number of elements. If passed arguments, does a search
585 on the resultset and counts the results of that.
587 Note: When using C<count> with C<group_by>, L<DBIX::Class> emulates C<GROUP BY>
588 using C<COUNT( DISTINCT( columns ) )>. Some databases (notably SQLite) do
589 not support C<DISTINCT> with multiple columns. If you are using such a
590 database, you should only use columns from the main table in your C<group_by>
597 return $self->search(@_)->count if @_ and defined $_[0];
598 return scalar @{ $self->get_cache } if @{ $self->get_cache };
600 my $count = $self->_count;
601 return 0 unless $count;
603 $count -= $self->{attrs}{offset} if $self->{attrs}{offset};
604 $count = $self->{attrs}{rows} if
605 $self->{attrs}{rows} and $self->{attrs}{rows} < $count;
609 sub _count { # Separated out so pager can get the full count
611 my $select = { count => '*' };
612 my $attrs = { %{ $self->{attrs} } };
613 if (my $group_by = delete $attrs->{group_by}) {
614 delete $attrs->{having};
615 my @distinct = (ref $group_by ? @$group_by : ($group_by));
616 # todo: try CONCAT for multi-column pk
617 my @pk = $self->result_source->primary_columns;
619 foreach my $column (@distinct) {
620 if ($column =~ qr/^(?:\Q$attrs->{alias}.\E)?$pk[0]$/) {
621 @distinct = ($column);
627 $select = { count => { distinct => \@distinct } };
628 #use Data::Dumper; die Dumper $select;
631 $attrs->{select} = $select;
632 $attrs->{as} = [qw/count/];
634 # offset, order by and page are not needed to count. record_filter is cdbi
635 delete $attrs->{$_} for qw/rows offset order_by page pager record_filter/;
637 my ($count) = (ref $self)->new($self->result_source, $attrs)->cursor->next;
643 Counts the results in a literal query. Equivalent to calling L</search_literal>
644 with the passed arguments, then L</count>.
648 sub count_literal { shift->search_literal(@_)->count; }
652 Returns all elements in the resultset. Called implicitly if the resultset
653 is returned in list context.
659 return @{ $self->get_cache } if @{ $self->get_cache };
663 if (keys %{$self->{collapse}}) {
664 # Using $self->cursor->all is really just an optimisation.
665 # If we're collapsing has_many prefetches it probably makes
666 # very little difference, and this is cleaner than hacking
667 # _construct_object to survive the approach
668 $self->cursor->reset;
669 my @row = $self->cursor->next;
671 push(@obj, $self->_construct_object(@row));
672 @row = (exists $self->{stashed_row}
673 ? @{delete $self->{stashed_row}}
674 : $self->cursor->next);
677 @obj = map { $self->_construct_object(@$_) } $self->cursor->all;
680 $self->set_cache(\@obj) if $self->{attrs}{cache};
686 Resets the resultset's cursor, so you can iterate through the elements again.
692 $self->{all_cache_position} = 0;
693 $self->cursor->reset;
699 Resets the resultset and returns the first element.
704 return $_[0]->reset->next;
711 =item Arguments: (\%values)
715 Sets the specified columns in the resultset to the supplied values.
720 my ($self, $values) = @_;
721 $self->throw_exception("Values for update must be a hash")
722 unless ref $values eq 'HASH';
723 return $self->result_source->storage->update(
724 $self->result_source->from, $values, $self->{cond}
732 =item Arguments: (\%values)
736 Fetches all objects and updates them one at a time. Note that C<update_all>
737 will run cascade triggers while L</update> will not.
742 my ($self, $values) = @_;
743 $self->throw_exception("Values for update must be a hash")
744 unless ref $values eq 'HASH';
745 foreach my $obj ($self->all) {
746 $obj->set_columns($values)->update;
753 Deletes the contents of the resultset from its result source. Note that this
754 will not run cascade triggers. See L</delete_all> if you need triggers to run.
762 if (!ref($self->{cond})) {
764 # No-op. No condition, we're deleting everything
766 } elsif (ref $self->{cond} eq 'ARRAY') {
768 $del = [ map { my %hash;
769 foreach my $key (keys %{$_}) {
771 $hash{$1} = $_->{$key};
772 }; \%hash; } @{$self->{cond}} ];
774 } elsif (ref $self->{cond} eq 'HASH') {
776 if ((keys %{$self->{cond}})[0] eq '-and') {
778 $del->{-and} = [ map { my %hash;
779 foreach my $key (keys %{$_}) {
781 $hash{$1} = $_->{$key};
782 }; \%hash; } @{$self->{cond}{-and}} ];
786 foreach my $key (keys %{$self->{cond}}) {
788 $del->{$1} = $self->{cond}{$key};
793 $self->throw_exception(
794 "Can't delete on resultset with condition unless hash or array"
798 $self->result_source->storage->delete($self->result_source->from, $del);
804 Fetches all objects and deletes them one at a time. Note that C<delete_all>
805 will run cascade triggers while L</delete> will not.
811 $_->delete for $self->all;
817 Returns a L<Data::Page> object for the current resultset. Only makes
818 sense for queries with a C<page> attribute.
824 my $attrs = $self->{attrs};
825 $self->throw_exception("Can't create pager for non-paged rs")
826 unless $self->{page};
827 $attrs->{rows} ||= 10;
828 return $self->{pager} ||= Data::Page->new(
829 $self->_count, $attrs->{rows}, $self->{page});
836 =item Arguments: ($page_num)
840 Returns a new resultset for the specified page.
845 my ($self, $page) = @_;
846 my $attrs = { %{$self->{attrs}} };
847 $attrs->{page} = $page;
848 return (ref $self)->new($self->result_source, $attrs);
855 =item Arguments: (\%vals)
859 Creates a result in the resultset's result class.
864 my ($self, $values) = @_;
865 $self->throw_exception( "new_result needs a hash" )
866 unless (ref $values eq 'HASH');
867 $self->throw_exception(
868 "Can't abstract implicit construct, condition not a hash"
869 ) if ($self->{cond} && !(ref $self->{cond} eq 'HASH'));
871 my $alias = $self->{attrs}{alias};
872 foreach my $key (keys %{$self->{cond}||{}}) {
873 $new{$1} = $self->{cond}{$key} if ($key =~ m/^(?:\Q${alias}.\E)?([^.]+)$/);
875 my $obj = $self->result_class->new(\%new);
876 $obj->result_source($self->result_source) if $obj->can('result_source');
884 =item Arguments: (\%vals)
888 Inserts a record into the resultset and returns the object.
890 Effectively a shortcut for C<< ->new_result(\%vals)->insert >>.
895 my ($self, $attrs) = @_;
896 $self->throw_exception( "create needs a hashref" )
897 unless ref $attrs eq 'HASH';
898 return $self->new_result($attrs)->insert;
901 =head2 find_or_create
905 =item Arguments: (\%vals, \%attrs?)
909 $class->find_or_create({ key => $val, ... });
911 Searches for a record matching the search condition; if it doesn't find one,
912 creates one and returns that instead.
914 my $cd = $schema->resultset('CD')->find_or_create({
916 artist => 'Massive Attack',
917 title => 'Mezzanine',
921 Also takes an optional C<key> attribute, to search by a specific key or unique
922 constraint. For example:
924 my $cd = $schema->resultset('CD')->find_or_create(
926 artist => 'Massive Attack',
927 title => 'Mezzanine',
929 { key => 'artist_title' }
932 See also L</find> and L</update_or_create>.
938 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
939 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
940 my $exists = $self->find($hash, $attrs);
941 return defined $exists ? $exists : $self->create($hash);
944 =head2 update_or_create
946 $class->update_or_create({ key => $val, ... });
948 First, search for an existing row matching one of the unique constraints
949 (including the primary key) on the source of this resultset. If a row is
950 found, update it with the other given column values. Otherwise, create a new
953 Takes an optional C<key> attribute to search on a specific unique constraint.
956 # In your application
957 my $cd = $schema->resultset('CD')->update_or_create(
959 artist => 'Massive Attack',
960 title => 'Mezzanine',
963 { key => 'artist_title' }
966 If no C<key> is specified, it searches on all unique constraints defined on the
967 source, including the primary key.
969 If the C<key> is specified as C<primary>, search only on the primary key.
971 See also L</find> and L</find_or_create>.
975 sub update_or_create {
977 my $attrs = (@_ > 1 && ref $_[$#_] eq 'HASH' ? pop(@_) : {});
978 my $hash = ref $_[0] eq 'HASH' ? shift : {@_};
980 my %unique_constraints = $self->result_source->unique_constraints;
981 my @constraint_names = (exists $attrs->{key}
983 : keys %unique_constraints);
986 foreach my $name (@constraint_names) {
987 my @unique_cols = @{ $unique_constraints{$name} };
989 map { $_ => $hash->{$_} }
990 grep { exists $hash->{$_} }
993 push @unique_hashes, \%unique_hash
994 if (scalar keys %unique_hash == scalar @unique_cols);
997 if (@unique_hashes) {
998 my $row = $self->single(\@unique_hashes);
1000 $row->set_columns($hash);
1006 return $self->create($hash);
1011 Gets the contents of the cache for the resultset.
1016 shift->{all_cache} || [];
1021 Sets the contents of the cache for the resultset. Expects an arrayref
1022 of objects of the same class as those produced by the resultset.
1027 my ( $self, $data ) = @_;
1028 $self->throw_exception("set_cache requires an arrayref")
1029 if ref $data ne 'ARRAY';
1030 my $result_class = $self->result_class;
1032 $self->throw_exception(
1033 "cannot cache object of type '$_', expected '$result_class'"
1034 ) if ref $_ ne $result_class;
1036 $self->{all_cache} = $data;
1041 Clears the cache for the resultset.
1046 shift->set_cache([]);
1049 =head2 related_resultset
1051 Returns a related resultset for the supplied relationship name.
1053 $artist_rs = $schema->resultset('CD')->related_resultset('Artist');
1057 sub related_resultset {
1058 my ( $self, $rel, @rest ) = @_;
1059 $self->{related_resultsets} ||= {};
1060 return $self->{related_resultsets}{$rel} ||= do {
1061 #warn "fetching related resultset for rel '$rel'";
1062 my $rel_obj = $self->result_source->relationship_info($rel);
1063 $self->throw_exception(
1064 "search_related: result source '" . $self->result_source->name .
1065 "' has no such relationship ${rel}")
1066 unless $rel_obj; #die Dumper $self->{attrs};
1068 my $rs = $self->search(undef, { join => $rel });
1069 my $alias = defined $rs->{attrs}{seen_join}{$rel}
1070 && $rs->{attrs}{seen_join}{$rel} > 1
1071 ? join('_', $rel, $rs->{attrs}{seen_join}{$rel})
1074 $self->result_source->schema->resultset($rel_obj->{class}
1084 =head2 throw_exception
1086 See Schema's throw_exception
1090 sub throw_exception {
1092 $self->result_source->schema->throw_exception(@_);
1097 XXX: FIXME: Attributes docs need clearing up
1099 The resultset takes various attributes that modify its behavior. Here's an
1104 Which column(s) to order the results by. This is currently passed
1105 through directly to SQL, so you can give e.g. C<year DESC> for a
1106 descending order on the column `year'.
1112 =item Arguments: (\@columns)
1116 Shortcut to request a particular set of columns to be retrieved. Adds
1117 C<me.> onto the start of any column without a C<.> in it and sets C<select>
1118 from that, then auto-populates C<as> from C<select> as normal. (You may also
1119 use the C<cols> attribute, as in earlier versions of DBIC.)
1121 =head2 include_columns
1125 =item Arguments: (\@columns)
1129 Shortcut to include additional columns in the returned results - for example
1131 $schema->resultset('CD')->search(undef, {
1132 include_columns => ['artist.name'],
1136 would return all CDs and include a 'name' column to the information
1137 passed to object inflation
1143 =item Arguments: (\@columns)
1147 Indicates which columns should be selected from the storage. You can use
1148 column names, or in the case of RDBMS back ends, function or stored procedure
1151 $rs = $schema->resultset('Employee')->search(undef, {
1154 { count => 'employeeid' },
1159 When you use function/stored procedure names and do not supply an C<as>
1160 attribute, the column names returned are storage-dependent. E.g. MySQL would
1161 return a column named C<count(employeeid)> in the above example.
1167 =item Arguments: (\@names)
1171 Indicates column names for object inflation. This is used in conjunction with
1172 C<select>, usually when C<select> contains one or more function or stored
1175 $rs = $schema->resultset('Employee')->search(undef, {
1178 { count => 'employeeid' }
1180 as => ['name', 'employee_count'],
1183 my $employee = $rs->first(); # get the first Employee
1185 If the object against which the search is performed already has an accessor
1186 matching a column name specified in C<as>, the value can be retrieved using
1187 the accessor as normal:
1189 my $name = $employee->name();
1191 If on the other hand an accessor does not exist in the object, you need to
1192 use C<get_column> instead:
1194 my $employee_count = $employee->get_column('employee_count');
1196 You can create your own accessors if required - see
1197 L<DBIx::Class::Manual::Cookbook> for details.
1201 Contains a list of relationships that should be joined for this query. For
1204 # Get CDs by Nine Inch Nails
1205 my $rs = $schema->resultset('CD')->search(
1206 { 'artist.name' => 'Nine Inch Nails' },
1207 { join => 'artist' }
1210 Can also contain a hash reference to refer to the other relation's relations.
1213 package MyApp::Schema::Track;
1214 use base qw/DBIx::Class/;
1215 __PACKAGE__->table('track');
1216 __PACKAGE__->add_columns(qw/trackid cd position title/);
1217 __PACKAGE__->set_primary_key('trackid');
1218 __PACKAGE__->belongs_to(cd => 'MyApp::Schema::CD');
1221 # In your application
1222 my $rs = $schema->resultset('Artist')->search(
1223 { 'track.title' => 'Teardrop' },
1225 join => { cd => 'track' },
1226 order_by => 'artist.name',
1230 If the same join is supplied twice, it will be aliased to <rel>_2 (and
1231 similarly for a third time). For e.g.
1233 my $rs = $schema->resultset('Artist')->search({
1234 'cds.title' => 'Down to Earth',
1235 'cds_2.title' => 'Popular',
1237 join => [ qw/cds cds/ ],
1240 will return a set of all artists that have both a cd with title 'Down
1241 to Earth' and a cd with title 'Popular'.
1243 If you want to fetch related objects from other tables as well, see C<prefetch>
1250 =item Arguments: (\@relationships)
1254 Contains one or more relationships that should be fetched along with the main
1255 query (when they are accessed afterwards they will have already been
1256 "prefetched"). This is useful for when you know you will need the related
1257 objects, because it saves at least one query:
1259 my $rs = $schema->resultset('Tag')->search(
1268 The initial search results in SQL like the following:
1270 SELECT tag.*, cd.*, artist.* FROM tag
1271 JOIN cd ON tag.cd = cd.cdid
1272 JOIN artist ON cd.artist = artist.artistid
1274 L<DBIx::Class> has no need to go back to the database when we access the
1275 C<cd> or C<artist> relationships, which saves us two SQL statements in this
1278 Simple prefetches will be joined automatically, so there is no need
1279 for a C<join> attribute in the above search. If you're prefetching to
1280 depth (e.g. { cd => { artist => 'label' } or similar), you'll need to
1281 specify the join as well.
1283 C<prefetch> can be used with the following relationship types: C<belongs_to>,
1284 C<has_one> (or if you're using C<add_relationship>, any relationship declared
1285 with an accessor type of 'single' or 'filter').
1291 =item Arguments: (\@array)
1295 The C<from> attribute gives you manual control over the C<FROM> clause of SQL
1296 statements generated by L<DBIx::Class>, allowing you to express custom C<JOIN>
1299 NOTE: Use this on your own risk. This allows you to shoot off your foot!
1300 C<join> will usually do what you need and it is strongly recommended that you
1301 avoid using C<from> unless you cannot achieve the desired result using C<join>.
1303 In simple terms, C<from> works as follows:
1306 { <alias> => <table>, -join-type => 'inner|left|right' }
1307 [] # nested JOIN (optional)
1308 { <table.column> = <foreign_table.foreign_key> }
1314 ON <table.column> = <foreign_table.foreign_key>
1316 An easy way to follow the examples below is to remember the following:
1318 Anything inside "[]" is a JOIN
1319 Anything inside "{}" is a condition for the enclosing JOIN
1321 The following examples utilize a "person" table in a family tree application.
1322 In order to express parent->child relationships, this table is self-joined:
1324 # Person->belongs_to('father' => 'Person');
1325 # Person->belongs_to('mother' => 'Person');
1327 C<from> can be used to nest joins. Here we return all children with a father,
1328 then search against all mothers of those children:
1330 $rs = $schema->resultset('Person')->search(
1333 alias => 'mother', # alias columns in accordance with "from"
1335 { mother => 'person' },
1338 { child => 'person' },
1340 { father => 'person' },
1341 { 'father.person_id' => 'child.father_id' }
1344 { 'mother.person_id' => 'child.mother_id' }
1351 # SELECT mother.* FROM person mother
1354 # JOIN person father
1355 # ON ( father.person_id = child.father_id )
1357 # ON ( mother.person_id = child.mother_id )
1359 The type of any join can be controlled manually. To search against only people
1360 with a father in the person table, we could explicitly use C<INNER JOIN>:
1362 $rs = $schema->resultset('Person')->search(
1365 alias => 'child', # alias columns in accordance with "from"
1367 { child => 'person' },
1369 { father => 'person', -join-type => 'inner' },
1370 { 'father.id' => 'child.father_id' }
1377 # SELECT child.* FROM person child
1378 # INNER JOIN person father ON child.father_id = father.id
1384 =item Arguments: ($page)
1388 For a paged resultset, specifies which page to retrieve. Leave unset
1389 for an unpaged resultset.
1395 =item Arguments: ($rows)
1399 For a paged resultset, specifies how many rows are in each page:
1403 Can also be used to simulate an SQL C<LIMIT>.
1409 =item Arguments: (\@columns)
1413 A arrayref of columns to group by. Can include columns of joined tables.
1415 group_by => [qw/ column1 column2 ... /]
1419 Set to 1 to group by all columns.
1423 Set to 1 to cache search results. This prevents extra SQL queries if you
1424 revisit rows in your ResultSet:
1426 my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
1428 while( my $artist = $resultset->next ) {
1432 $rs->first; # without cache, this would issue a query
1434 By default, searches are not cached.
1436 For more examples of using these attributes, see
1437 L<DBIx::Class::Manual::Cookbook>.