[Dbix-class] get_columns and overloaded column accessors

Francesc Romà i Frigolé francesc.roma+dbix at gmail.com
Wed Oct 20 11:53:03 GMT 2010


Hello,

I'm using overloaded column accessors as described in the
Cookbok<http://search.cpan.org/%7Efrew/DBIx-Class-0.08123/lib/DBIx/Class/Ma=
nual/Cookbook.pod#OVERLOADING_METHODS>.
For a given row, I'd like to get a hash with all the column names/value
pairs like Row->get_columns returns. However, get_columns returns the actual
column values, not the ones created with the custom overloaded accessors.
get_inflated_columns behaves the same way.

I could get the data I want with a loop but it's not very elegant:

      foreach my $col ( $row->columns ) {
          $row_href->{$col} =3D $obj->$col;
      }

Is there a better way of doing this? The reason why I want the hash is to
pass the data to my view in a Catalyst application.

BTW, the documentation of Row->get_column says "Returns a raw column value
from the row object, if it has already been fetched from the database or set
by an accessor." Which made me think it would do what I need, but it
doesn't.

To illustrate my point, I took the code in DBIx::Class::Manual::Example, and
added the following accessor in the result Track:

#__PACKAGE__->add_columns(qw/ trackid cd title /);
__PACKAGE__->add_columns(qw/ trackid cd /);

sub title {
    my $self =3D shift;

    my $ti =3D $self->_title(@_);

    return $ti . " -> my favourite song! ";
}

Now if I test the code like this:

get_tracks_by_cd('Bad');
get_tracks_by_artist('Michael Jackson');

get_cd_by_track('Stan');

sub get_tracks_by_cd {
  my $cdtitle =3D shift;
  print "get_tracks_by_cd($cdtitle):\n";
  my $rs =3D $schema->resultset('Track')->search(
    {
      'cd.title' =3D> $cdtitle
    },
    {
      join     =3D> [qw/ cd /],
    }
  );

  while (my $track =3D $rs->next) {
    print $track->title . "\n";
    my $track_href =3D { $track->get_columns };
    print $track_href->{title} . "\n";
  }
  print "\n";
}

I get:

get_tracks_by_cd(Bad):
Leave Me Alone -> my favourite song!
Leave Me Alone
Smooth Criminal -> my favourite song!
Smooth Criminal
Dirty Diana -> my favourite song!
Dirty Diana


As you can see, the overloaded accessor works with the row object, but is
not used by get_columns.

Thanks,
Francesc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.scsys.co.uk/pipermail/dbix-class/attachments/20101020/f4a=
a270c/attachment.htm


More information about the DBIx-Class mailing list