1

我正在使用 Laravel 5 中的简单 API,由于数据库中有大量数据,我想进行分页。

这是对路由 api/v1/words 的 GET 请求调用的方法

public function index()
    {
        //$words = Word::all();
        $limit = Input::get('limit') ?: 3;
        $words = Word::paginate($limit);
        //dd(get_class_methods($words));
        return $this->respondWithPagination($words);
    }
                     .
                     .  
                     .

    public function respondWithPagination($words)
    {
        return $this->respond([
            'words' => $this->wordTransformer->transformCollection($words->all()),
            'paginator' => [
                'totalCount' => $words->getTotal(),
                'totalPages' => ceil($words->getTotal() / $words->getPerPage()),
                'currentPage' => $words->getCurrentPage(),
                'limit' => $words->getPerPage(),
                'previousPageUrl' => $words->previousPageUrl(),
                'nextPageUrl' => $words->nextPageUrl()
            ]
        ]);
    }

但是我的日志给了我这个错误:

[2015-04-17 09:50:28] local.ERROR: exception 'ErrorException' with message 'call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\Eloquent\Collection' does not have a method 'getTotal'' in /home/vagrant/Code/zadarplus2/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php:463
    Stack trace:
    #0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'call_user_func_...', '/home/vagrant/C...', 463, Array)
    #1 /home/vagrant/Code/zadarplus2/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php(463): call_user_func_array(Array, Array)
    #2 /home/vagrant/Code/zadarplus2/app/Http/Controllers/WordController.php(90): Illuminate\Pagination\AbstractPaginator->__call('getTotal', Array)
    #3 /home/vagrant/Code/zadarplus2/app/Http/Controllers/WordController.php(90): Illuminate\Pagination\LengthAwarePaginator->getTotal()
    #4 /home/vagrant/Code/zadarplus2/app/Http/Controllers/WordController.php(43): App\Http\Controllers\WordController->respondWithPagination(Object(Illuminate\Pagination\LengthAwarePaginator))
    #5 [internal function]: App\Http\Controllers\WordController->index()
    #6 /home/vagrant/Code/zadarplus2/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(246): call_user_func_array(Array, Array)

我究竟做错了什么?

4

1 回答 1

1

$words是一个Illuminate\Pagination\Paginator 对象(请参阅此处的文档)。

你调用了一个不属于的方法

  • 既不Paginator上课
  • 也不是通过动态调用访问其底层Collection(另请参阅此处的文档)。

彻底探索/研究文档以了解所需方法的正确拼写。


提示:

  • count():获取 ( Paginator) 当前页面 (参考) 的项目数。
  • count():计算(底层)Collection参考)中的项目数。
于 2015-04-17T12:37:12.163 回答