简体   繁体   English

DBIx :: Class:ResultSet获取大小

[英]DBIx::Class:ResultSet get size

I'm using DBIx::Class to retrieve results like so: 我正在使用DBIx :: Class来检索结果,如下所示:

my $users = $c->model('DB::User')->search(
    { active_yn => 'y', client_yn => 'n' },
    {   
        columns => [qw/id first_name last_name username email/],
        order_by => ['last_name'],
        page     => ($c->req->param('page') || 1), 
        rows     => 20, 
    }   
); 

However, once I get the results I want to know how many have been returned, but I can not seem to find a method provided that tells me this. 但是,一旦我得到结果,我想知道已经返回了多少,但我似乎无法找到一个告诉我的方法。 Does anyone know how to get the count of $users after executing this query? 有谁知道在执行此查询后如何获取$users的数量? Thanks! 谢谢!

You can do: 你可以做:

my $num_users = $users->count;

The object is also numerically overloaded to return the count: 该对象也在数值上重载以返回计数:

my $num_users = $users + 0;

For reference, see https://metacpan.org/module/DBIx::Class::ResultSet#count . 有关参考,请参阅https://metacpan.org/module/DBIx::Class::ResultSet#count

UPDATE: On why resultset needs to issue a separate query to get the count. 更新:为什么结果集需要发出单独的查询来获取计数。

Note the main description of the resultset class: 请注意结果集类的主要描述:

A ResultSet is an object which stores a set of conditions representing a query. ResultSet是存储表示查询的一组条件的对象。 It is the backbone of DBIx::Class (ie the really important/useful bit). 它是DBIx :: Class的主干(即真正重要/有用的位)。

No SQL is executed on the database when a ResultSet is created, it just stores all the conditions needed to create the query. 创建ResultSet时,不会在数据库上执行SQL,它只存储创建查询所需的所有条件。

... ...

The query that the ResultSet represents is only executed against the database when these methods are called: "find", "next", "all", "first", "single", "count". 只有在调用这些方法时,才会对数据库执行ResultSet表示的查询:“find”,“next”,“all”,“first”,“single”,“count”。

In other words, the resultset doesn't have the count until it queries for it. 换句话说,结果集在查询之前没有计数。

When you iterate through the resultset using next it will keep a stash of the records it has read from the database, but it will discard those records as it gives them to you, which means it can't give you the count from what it has read. 当你使用next迭代结果集时,它将保留它从数据库中读取的记录的藏匿处,但它会丢弃那些记录,因为它会将它们提供给你,这意味着它无法从你拥有的记录中获得数量。读。 You need to ask for them to be cached if you want to do that. 如果你想这样做,你需要要求它们被缓存。

my $resultset = $schema->resultset('Artist')->search( undef, { cache => 1 } );
my @records = $resultset->all;
my $count = $resultset->count; # this uses the count of the cached records

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM