perldbidbix-class

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


I'm new to DBIx::Class. I'm 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'm sure I have misunderstood the concept of DBIC. How can I get the data of all columns only?


Solution

  • 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;