gpt4 book ai didi

perl - DBIx::Class:ResultSet 获取大小

转载 作者:行者123 更新时间:2023-12-01 04:49:19 24 4
gpt4 key购买 nike

我正在使用 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,
}
);

但是,一旦我得到结果,我想知道返回了多少,但我似乎找不到提供告诉我这一点的方法。有谁知道如何获得 $users的计数执行此查询后?谢谢!

最佳答案

你可以做:

my $num_users = $users->count;

该对象也在数值上重载以返回计数:
my $num_users = $users + 0;

引用 https://metacpan.org/module/DBIx::Class::ResultSet#count .

更新:关于为什么结果集需要发出单独的查询来获取计数。

请注意结果集类的主要描述:

A ResultSet is an object which stores a set of conditions representing a query. It is the backbone of DBIx::Class (i.e. the really important/useful bit).

No SQL is executed on the database when a ResultSet is created, it just stores all the conditions needed to create the query.

...

The query that the ResultSet represents is only executed against the database when these methods are called: "find", "next", "all", "first", "single", "count".



换句话说,结果集在查询它之前没有计数。

当您使用 next 遍历结果集时它会保存从数据库中读取的记录,但它会在将这些记录提供给您时丢弃这些记录,这意味着它无法为您提供读取的数量。如果您想这样做,您需要要求缓存它们。
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

关于perl - DBIx::Class:ResultSet 获取大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com