1

我试图弄清楚为什么我无法访问元素内部的祝福引用:

这是我的模块:

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' },
      },
],

这是我要测试的子:

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

如果我使用 $_->alias 我得到以下返回:

$ ./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
        };

如果我使用 $_->alias->alias,我会收到一个错误:

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

我有点困惑,因为 Dumper 输出显示 Alias 的值是有福的,这似乎与错误消息相矛盾。

4

1 回答 1

1

Dumper 输出显示$_->alias 返回哈希引用,而不是对象。要访问结构中的别名对象,您需要以下内容:

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

要访问该对象的别名方法:

$_->{rows}[0]{alias)->alias;
于 2012-08-02T13:46:43.867 回答