【问题标题】:Get total of Collection获取收藏总数
【发布时间】:2020-08-23 10:27:20
【问题描述】:

在查询中使用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();

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

【问题讨论】:

    标签: php laravel laravel-5 lumen laravel-6


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      在第一个示例中,您的呼叫 paginate() 在查询构建器中... (在你做之前 ->get())

      在您的第二个示例中,paginate() 调用在集合上,在您使用 ->get() 检索结果后

      $records 在两者中是不同的,第一个是查询生成器,第二个是集合

      【讨论】:

        【解决方案3】:

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

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

        这将返回一个LengthAwarePaginator 实例,它有很多有用的方法:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多