首页 > 解决方案 > laravel paginate 1000 last Record with relationship

问题描述

如何获取最后 1000 条有关系的记录并对其进行分页?

我试试这个,但这会返回所有数据

$logbooks = $this->log_book->orderBy('created_at','desc')->skip(10000)->take(1000)->paginate(100);

标签: phplaravelpagination

解决方案


只有我能做的是使用这个宏在集合上进行分页,所以将此代码添加到我的 AppServiceProvider

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
    $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

    return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
        'path' => LengthAwarePaginator::resolveCurrentPath(),
        'pageName' => $pageName,
    ]);
});

然后我将对集合进行分页

$logbooks = $this->log_book->orderBy('created_at','desc')->limit(1000)->get();
$logbooks->paginate(100);

推荐阅读