Convert a DBIx::Class::Result into a hash

2019-02-27 11:22发布

问题:

Using DBIx::Class, I found a solution to my issue, thankfully. But I'm sure there has to be a nicer way.

my $record = $schema->resultset("food")->create({name=>"bacon"});

How would I turn this record into a simple hashref instead of having to make this call right after.

my record = $schema->resultset("food")->search({name=>"bacon"})->hashref_array();

Ideally I want to be able to write a code snippet as simple as

 {record=> $record} 

instead of

{record => {name => $record->name, $record->food_id, ...}}

This would drive me insane with a table that has alot more columns.

回答1:

I assume you're talking about DBIx::Class?

my $record = $schema->resultset("food")->create({name=>"bacon"});
my %record_columns = $record->get_columns;

# or, to get a HashRef directly
my $cols = { $record->get_columns };

# or, as you've asked for
my $foo = { record => { $record->get_columns } };


回答2:

What you're looking for is included in DBIx::Class as DBIx::Class::ResultClass::HashRefInflator.