Perl How to use DBIx::Class to return data beautifully

Viewed 298

I'am new to DBIx::Class. Iam using it for an API to retun data from my DB and i want to recreate a SELECT * FROM table with DBIC. With DBI it worked well for me.
What is the best approach to return data "beautiful"?
I want to return the data in a array of hashes like:

[
  {
    id => 123,
    name => 'name',
    ....
  }
]

But with my @rs = $schema->resultset('Product')->all; return \@rs;. I get not the output i want. On inspecting the objects with Data::Dumper i get the following:

$VAR1 = bless( {
              '_column_data' => {
                                  'name' => 'test',
                                  'id' => 123'
                                },
              '_result_source' => $VAR1->{'_result_source'},
              '_in_storage' => 1
            }, 'DB::Schema::Result::Product' );

I'am sure i missunderstood the concept of DBIC.
How can i get the data of all colums only? Thank you all for Help!

3 Answers

Data::Dumper just spills the guts of a data structure. That's the guts of a DB::Schema::Result::Product object which represents a single row of the Product table.

If you want pretty output from an object, you need to ask the object for that. You can call DBIx::Class::Row methods on them. If you want just the row data from the object, use get_columns or get_inflated_columns. They return a hash, so you need to take a reference.

my @rows = map { my %h = $_->get_columns; \%h } @rs;

Simplest way I can think is get_inflated_columns method.

map {{$_->get_inflated_columns}} $rs->all

Consider using Data::Dump and if you really want something beautiful, Data::Printer.

my @rs = map {$_->_column_data} $schema->resultset('Product')->all

? That said, by convention a field with a leading underscore is a "private" field, likely to be undocumented or underdocumented, or subject to change in future implementations without notice, and you should be wary of accessing them directly.

Since the point of DBIx::Class is to translate database rows into objects, you should treat your result set like an array of objects. To downcast it to a hash suitable for use with Data::Dumper, you could do something like

my @rs = map { { name => $_->name, id => $_->id } } $schema->resultset('Product')->all
Related