【问题标题】:How can I limit results when the current page is 1?当前页面为 1 时如何限制结果?
【发布时间】:2020-10-13 03:37:53
【问题描述】:

如果当前页面为 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,无论如何我可以做我想做的事?

【问题讨论】:

  • 这会给你一组不同的结果。如果第一页有 4 个,第二页有 6 个,分页器会假定您的第一页有 6 个,而第二个则跳过其中两个。
  • 我不知道我是否在寻找那个@Cid

标签: php laravel eloquent laravel-7


【解决方案1】:

您可能需要做一个自定义解决方案:

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

【讨论】:

    【解决方案2】:

    你可以试试:

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

    【讨论】:

    • 这会在第二页跳过 2 个结果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2016-07-17
    • 2019-11-12
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多