当前页数为1时如何限制结果?

如果当前页面为 1,我想显示 4 个结果;如果当前页面 > 1,则显示 6 个结果,我的控制器中的逻辑是:


    public function emfoco()

    {

        if ($paginator->currentPage() == 1) {

            $emfoco = Noticia::orderBy('created_at','desc')->paginate(4,'*','f');

        } else {

            $emfoco = Noticia::orderBy('created_at','desc')->paginate(6,'*','f');

        }

        return view('em-foco')->with(['emfoco'=>$emfoco]);;

    }

但这不起作用,因为我无法访问控制器中的 $paginator,无论如何可以做我想做的事情吗?


慕娘9325324
浏览 212回答 2
2回答

慕村225694

您可能需要执行自定义解决方案:    public function emfoco()    {        if (request()->input('f', 1) == 1) {            $emfocoCount = Noticia::count();            $emfocoCollection = Noticia::orderBy('created_at','desc')->take(4);            $emfoco = new LengthAwarePaginator($emfocoCollection, $emfocoCount, 6, LengthAwarePaginator::resolveCurrentPage('f'), [ 'pageName' => 'f' ]);        } else {            $emfocoCount = Noticia::count();            $emfocoCollection = Noticia::orderBy('created_at','desc')                   // If this is e.g. page 5 you skip the 4 on page 1 and the 18 on the 3 other previous pages                  ->skip(4+6*(LengthAwarePaginator::resolveCurrentPage('f')-2))->take(6);            $emfoco = new LengthAwarePaginator($emfocoCollection, $emfocoCount, 6, LengthAwarePaginator::resolveCurrentPage('f'), [ 'pageName' => 'f' ]);        }        $emfoco->setPath($request->getPathInfo()); // You might need this too        return view('em-foco')->with(['emfoco'=>$emfoco]);;    }请注意,在这两种情况下,分页器都设置为假定每页有 6 个结果,尽管事实上第 1 页中只有 4 个结果。这是因为该数字基本上只是决定总页数。(我认为)这将导致计算出正确的总页数,尽管第一个结果将有 4 个结果(因为这就是我们要传递的所有结果)更新:如果您有 6 个总结果,您可能会得到错误的页数,因此要修复,您可以将$emfocoCount+2总结果数传递过去,以补偿第一页的结果比正常情况下少 2 个的事实。

梦里花落0921

你可以尝试一下:public function emfoco(){    if (!request()->get('f') || request()->get('f') == 1) {        $emfoco = Noticia::orderBy('created_at', 'desc')->paginate(4, null, 'f');    } else {        $emfoco = $emfoco->skip(4 + ((request()->get('f') - 2) * 6))->take(6);        $emfoco = new LengthAwarePaginator($emfoco->get(), Noticia::count(), 6, request()->get('f'));    }    return view('em-foco')->with(['emfoco' => $emfoco]);;}
打开App,查看更多内容
随时随地看视频慕课网APP