获取集合总数

Get total of Collection

如何在查询中使用 skiptake 后获得记录总数?

代码工作:

$records = Model::where('active', 1)
                 ->skip(($page -1 ) * $max)
                 ->take($max);
// List of records
$data = $records->get()

//Total of all records including the skip records
$total = $records->paginate()->total();

我想要这种方式,但代码不起作用:

$records = Model::where('active', 1)
                 ->skip(($page -1 ) * $max)
                 ->take($max)->get();

//Not Working 
$total = $records->paginate()->total();

//Not Working 
$total = $records->total();

//Not Working wrong result
$total = $records->count();

如何获取集合中的所有总记录?

直接在您的模型上使用paginate()方法:

$records = Model::where('active', 1)->paginate($recordsPerPage);

那将return一个LengthAwarePaginator实例,里面有很多有用的方法:

https://laravel.com/api/7.x/Illuminate/Contracts/Pagination/LengthAwarePaginator.html

$records->total()$records->perPage()

在第一个示例中,您的调用 paginate() 是在查询生成器上... (在你做之前 ->get())

在您的第二个示例中,在您使用 ->get()

检索到结果后,集合中调用了 paginate()

$records 在两者中都是不同的东西,首先是查询生成器,其次是集合

试试这个

$records = Model::where('active', 1)
                 ->skip(($page -1 ) * $max)
                 ->take($max)->get();

$total = count($records);