为什么 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);
谢谢你的帮助;)
最佳答案
paginate
工作正常,但是 sortBy
方法给您带来了问题,因为当您使用 sortBy
时它会返回一个新集合.
最后,您的 $shops
是 Illuminate\Support\Collection
的实例,而不是 Illuminate\Pagination\LengthAwarePaginator
的实例。
你可以这样尝试:
$paginated_shops = Shop::whereIn('id',$shopIds)
->with('deals')
->with('deals.likes')
->paginate($this->perPage);
$shops = $paginated_shops->sortBy(function($likes) {
return $likes->count();
});
$shops = new LengthAwarePaginator($shops, $paginated_shops->total(), $paginated_shops->perPage());
记得在类的顶部添加use
语句:
use Illuminate\Pagination\LengthAwarePaginator;
关于php - Laravel 5.3 对 sortBy 集合的分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41200312/