为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕娘9325324 2023-06-24 18:35:48
如果当前页面为 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,无论如何可以做我想做的事情吗?
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

您可能需要执行自定义解决方案:


    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 个的事实。


查看完整回答
反对 回复 2023-06-24
?
梦里花落0921

TA贡献1772条经验 获得超6个赞

你可以尝试一下:


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]);;

}


查看完整回答
反对 回复 2023-06-24
  • 2 回答
  • 0 关注
  • 160 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号