Search code examples
perlrose-db-object

PERL | Blessed object in hash | Rose::DB::Object


I'm trying to figure out why I cannot access a blessed reference inside of an element:

This is my module:

package Test::Node

__PACKAGE__->meta->setup(
    table   => 'node',

    columns => [
        id                             => { type => 'serial', not_null => 1 },
        name                           => { type => 'varchar', length => 128, not_null => 1 },
    ],

    primary_key_columns => [ 'id' ],

    relationships =>
    [ 
      alias =>
      { 
        type       => 'one to many',
        class       => 'Test::Alia',
        column_map => { id => 'asset_id' },
      },
],

This is the sub that I am calling to test:

sub SearchNode {
  my $self = shift;
  my ($opts) = shift;
  my %query = (name => { like => "$opts->{name}%"});
  my %object = (with_objects => ['alias']);
  $object{query} = [%query] if $opts->{name};

  my $records = Test::Node::Manager->get_node(%object);
  my $i = 0;  
  my $record = {}; 
  $record->{page} = 1;
  $record->{total} = 1;
  foreach (@$records) {
    my %items =(
      id => $_->id,
      name => $_->name,
      alias => $_->alias->alias
    );  
    $record->{rows}[$i] = \%items; 
    $i++;
  }   
  $record->{records} = $i; 
  return $record;
}

If I use $_->alias I get the following returned:

$ ./search.pl 
$VAR1 = {
          'page' => 1,
          'records' => 1,
          'rows' => [
                      {
                        'name' => 'test.localhost.net',
                        'id' => '1234',
                        'alias' => bless( {
                                            'node_id' => '1234',
                                            'id' => '5678',
                                            'alias' => 'server1.localhost.net'
                                          }, 'Test::Alia' )
                      }
                    ],
          'total' => 1
        };

If I use $_->alias->alias, I receive an error:

./search.pl 
Can't call method "alias" on unblessed reference at /usr/local/lib/perl/Test/Node.pm line 41.

I'm abit confused since the Dumper output shows that the value of Alias is blessed which seems to contradict the error message.


Solution

  • The Dumper output shows that $_->alias return a hash-ref, not an object. To access the alias-object within the structure, you need something like:

    $_->{rows}[0]{alias};
    

    To access the alias-method of that object:

    $_->{rows}[0]{alias)->alias;