【问题标题】:mojolicious loop through the results of DBIx::Class::Ruleset->search in templatemojolicious 循环遍历 DBIx::Class::Ruleset-> 在模板中搜索的结果
【发布时间】:2014-11-30 21:45:02
【问题描述】:

注意。实际上,这段代码运行良好,只是我的路线中有一个错误。 我会把问题留在这里,以防它对某人有用......

我不确定如何在 Mojolicious 模板中访问搜索结果

比如我试过这个,不行:

sub list {
   my $self= shift;
   #Return a list of questions
   my @list = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }});
   $self->stash(list => \@list);
}

然后在我的模板中是

% for my $item (@$list) {
  <%= $item->question %> 
  <%= $item->explanation %> <br />
% }

但是这会产生错误

Not an ARRAY reference at template line x (where line x is the line containing @$list)

我尝试了很多其他方法。
如果我在列表上下文中调用搜索并转储结果,我可以看到我得到了一个 'Schema::Result::Question' 对象的列表 - 没错。

我只是不确定如何循环访问和访问模板中的数据?

【问题讨论】:

    标签: perl mojolicious


    【解决方案1】:
    $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }})
    

    返回一个结果集。

    你可以打电话 -> 就这样(你错过了-&gt;all

    my @list = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }})->all;
    

    或者,您可以像这样遍历结果集:

    my $rs = $self->db->resultset('Question')->search({}, {order_by => { -desc => 'q_order' }});
    while ( my $question = $rs->next ){
    # do things with $question
    }
    

    这不会立即获取所有这些问题,但由于它是一个结果集,它仅在被调用时执行(即您开始迭代)。

    这可能是第二种方法的优势。

    【讨论】:

    • 如果这回答了您的问题,请告诉我,您应该调用 ->all 来获取列表,我敢肯定,但错误消息不太适合我,也许还有另一个问题。 ..
    • 感谢您的输入,不,添加 ->all 会从 ->search 生成相同的结果。问题似乎是 mojolicious 不喜欢被解析的祝福对象列表(这是列表中的内容)。
    • 其实也不是这样。我将特定结果映射到一个哈希数组(我的@result = map { {question => $_->question, explain => $_->explanation} } @list;)并发送它,但仍然失败同样的错误。
    • Doh,我在处理路由的代码中有一个直接错误,所以我实际上并没有取消引用 @$list,因此它不是哈希。也许代码会给某人做一个有用的例子......
    • 我发现我可以做到 ,效果很好。很有用
    猜你喜欢
    • 2013-03-08
    • 2013-09-14
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2015-12-25
    • 2010-12-17
    相关资源
    最近更新 更多