为什么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);
感谢您的帮助;)
答案 0 :(得分: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());
请记住在课程顶部添加use
语句:
use Illuminate\Pagination\LengthAwarePaginator;
答案 1 :(得分:1)
谢谢你们!
我解决了这个问题
$shopIds = Follower::whereUserId($user->id)->orderBy('created_at','desc')->get()->pluck('shop_id')->toArray();
$shopIds = Shop::whereIn('id',$shopIds)->with('deals')->with('deals.likes')->get()->sortBy(function($likes) {
return $likes->count();
})->pluck('id')->toArray();
$orderedIds = implode(',',$shopIds);
$shops = Shop::whereIn('id', $shopIds)->whereNotIn('user_id', [$user->id])->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))->paginate($this->perPage);
dd($shops);
现在我有一个Illuminate \ Pagination \ LengthAwarePaginator的实例
感谢的
答案 2 :(得分:0)
就像@Amit提到的那样,$ shops是一个集合,因此不是LengthAwarePaginator。你将不得不构建分页器并自己切片......不要太复杂......
例如,让我们假设您正在按照您的路线,呼叫您的控制器...然后将结果返回到视图...现在该路线将通过请求中的分页信息获得请求,您工作是将结果$ shop放到一个数组中,将数组切成适合页面的结果并将其返回到您的视图...我没有运行此代码...所以以此为例...但是它看起来像是:
public function yourController{
// This will return a collection... we will convert it to array later
$shops = Shop::whereIn('id',$shopIds)->with('deals')->with('deals.likes')->paginate($this->perPage)->sortBy(function($likes) {
return $likes->count();
});
$shopsArray = $shops->toArray();
// Here we deal with the slicing... you need to slice the page you are
// at the paging info is in the request...
// this basically gets the request's page variable... or defaults to 1
$page = Paginator::resolveCurrentPage('page') ?: 1;
// Assume 15 items per page... so start index to slice our array
$startIndex = ($page - 1) * 15;
// Length aware paginator needs a total count of items... to paginate properly
$total = count($shopsArray);
// Eliminate the non relevant items by slicing the array to page content...
$results = array_slice($shopsArray, $startIndex, 15);
$result = new LengthAwarePaginator($results, $total, 15, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
return view('yourView', compact('result'));
}