Yii2 implements the "previous, next" function code example, yii2 next
I recently wrote a brief answer to the article details page. I need to add the previous article and the next button at the bottom of the page to analyze it. The most basic requirement is the article title and id (as a parameter ).
The first thought is to add or subtract 1 from the current id, but considering that if some IDs are lost, the following code is available to query records larger and smaller than the current id and limit them to one.
The Code is as follows. For more information, see.
Controller
// Query the previous article $ prev_article = your model: find ()-> andFilterWhere (['<', 'id', $ id]) -> andFilterWhere ([other conditions)-> orderBy (['id' => SORT_DESC])-> limit (1)-> one (); // query the next-Article $ next_article = your model: find ()-> andFilterWhere (['>', 'id', $ id]) -> andFilterWhere (other conditions)-> orderBy (['id' => SORT_ASC])-> limit (1)-> one (); $ model ['prev _ article'] = ['url' =>! Is_null ($ prev_article )? Url: current (['id' => $ prev_article-> id]): 'javascript:; ', 'title' =>! Is_null ($ prev_article )? $ Prev_article-> title: 'no longer',]; $ model ['Next _ article'] = ['url' =>! Is_null ($ next_article )? Url: current (['id' = >$ next_article-> id]): 'javascript:; ', 'title' =>! Is_null ($ next_article )? $ Next_article-> title: 'no longer',]; return $ this-> render ('view', 'model' => $ model ,);
View
<Div class = "left"> <p> previous: <a href = "<? = $ Model ['prev _ article'] ['url']?> "> <? = $ Model ['prev _ article'] ['title']?> </A> </p> </div> <div class = "right"> <p> next article: <a href = "<? = $ Model ['Next _ article'] ['url']?> "> <? = $ Model ['Next _ article'] ['title']?> </A> </p> </div>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.