Laravel 5.3对sortBy集合的分页

use*_*349 3 php mysql collections laravel eloquent

为什么paginate方法不适用于此示例?

$shopIds = Follower::whereUserId($user->id)->orderBy('created_at','desc')->get()->pluck('shop_id')->toArray();
            $shops = Shop::whereIn('id',$shopIds)->with('deals')->with('deals.likes')->paginate($this->perPage)->sortBy(function($likes) {
                return $likes->count();
            });
            dd($shops);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

感谢帮助 ;)

Ami*_*pta 5

paginate只是工作正常,但该sortBy方法正在为您创建问题,因为当您使用sortBy它时返回一个新的集合.

所以最后你$shops的实例Illuminate\Support\Collection不是Illuminate\Pagination\LengthAwarePaginator.

您可以尝试:

$pagianted_shops = Shop::whereIn('id',$shopIds)
                  ->with('deals')
                  ->with('deals.likes')
                  ->paginate($this->perPage);

$shops = $pagianted_shops->sortBy(function($likes) {
        return $likes->count();
    });

$shops = new LengthAwarePaginator($shops, $pagianted_shops->total(), $pagianted_shops->perPage());
Run Code Online (Sandbox Code Playgroud)

请记住use在类的顶部添加语句:

use Illuminate\Pagination\LengthAwarePaginator;
Run Code Online (Sandbox Code Playgroud)

  • 这在 2021 年对我有帮助:) 非常感谢。 (2认同)