亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當前頁數為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 關注
  • 200 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號