【问题标题】:Laravel 8 - Why can I not paginate this? [duplicate]Laravel 8 - 为什么我不能分页? [复制]
【发布时间】:2021-08-25 23:08:16
【问题描述】:

我有一个 Laravel API 调用,我想对结果进行分页,但似乎找不到可行的方法。我的电话是这样的:

public function index(Request $request){
    $per_page = $request->input('per_page');

    if(!$per_page)
        $per_page=20;

    $creditos = Prestacion::all();
    $creditos = $creditos->paginate($per_page);
    return $this->collection($creditos, new PrestacionTransformer);
}

这会返回错误:

“方法 Illuminate\Database\Eloquent\Collection::paginate 不存在。”

【问题讨论】:

    标签: php laravel laravel-8 query-builder


    【解决方案1】:

    这是因为您在分页之前运行查询。 检查这一行:

    $creditos = Prestacion::all();
    

    all() 方法执行查询。这意味着$creditos 现在是Collection 的实例,而不是QueryBuilder。这就是原因。类中不存在paginate() 方法。

    你应该这样做:

    $creditos = Prestacion::paginate();
    
    return $this->collection($creditos, new PrestacionTransformer);
    

    这应该适合你。

    【讨论】:

    • 好的,我想我明白了,但现在我收到错误“参数 1 传递给 Dingo\\Api\\Http\\Response\\Factory::collection() 必须是Illuminate\\Support\\Collection,给定的 Illuminate\\Pagination\\LengthAwarePaginator 实例"
    • @IvánFloresVázquez,尝试使用return $this->collection(collect(Prestacion::all()), new PrestacionTransformer);
    • @steven7mwesigwa 现在它说“无法找到 \"App\\Models\\PrestamosCreditos\\Prestacion\" 类的绑定变压器”。而且,这不会返回整个集合,而不是分页吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    相关资源
    最近更新 更多