Prepared 1.002
[dbsrgits/DBIx-Class-ResultSet-HashRef.git] / lib / DBIx / Class / ResultSet / HashRef.pm
index 17dabe0..427ab01 100644 (file)
@@ -2,10 +2,11 @@ package DBIx::Class::ResultSet::HashRef;
 
 use warnings;
 use strict;
+use Carp;
 use base qw( DBIx::Class::ResultSet );
 use DBIx::Class::ResultClass::HashRefInflator;
 
-our $VERSION = '1.001';
+our $VERSION = '1.002';
 
 =head1 NAME
 
@@ -83,10 +84,34 @@ sub hashref_first {
     return shift->hashref_rs->first;
 }
 
+=head2 hashref_pk( )
+
+Calls hashref_array and returns a reference to a hash containing the primary key. For each key the corresponding value is a reference to a hash of the resultset inflated by L<DBIx::Class::ResultClass::HashRefInflator>.
+
+    my $hashref_pk = $schema->resultset('User')->search( { } )->hashref_pk;
+    print Dumper $hashref_pk
+
+=cut
+
+sub hashref_pk{
+    my $self = shift;
+    my @primary_columns = $self->result_source->primary_columns;
+    croak "Multi-column primary keys are not supported." if (scalar @primary_columns > 1 );
+    croak "No primary key found." if (scalar @primary_columns == 0 );
+    my $primary_key = shift @primary_columns;
+    my %hash_pk = ();
+    %hash_pk = map { $_->{$primary_key} => $_ } $self->hashref_array;
+    return wantarray ? %hash_pk : \%hash_pk ;
+}
+
 =head1 AUTHOR
 
 Johannes Plunien E<lt>plu@cpan.orgE<gt>
 
+=head1 CONTRIBUTORS
+
+Robert Bohne E<lt>rbo@cpan.orgE<gt>
+
 =head1 COPYRIGHT AND LICENSE
 
 Copyright 2008 by Johannes Plunien