Code example for implementing 'previous article, next article' function in yii2

高洛峰
Release: 2023-03-05 13:10:01
Original
1288 people have browsed it

I recently made a short answer article details page. I need to add the previous article and next article buttons at the bottom of the page. After analysis, the most basic need is the title and id of the article (as parameters).

At first I thought of adding or subtracting 1 to the current id, but considering that it would be wrong if part of the id was lost, I queried records larger and smaller than the current id respectively and limited them to one, so I came up with the following code.

The code is as follows, please tell me if it is wrong.

In controller

//查询上-篇文章
    $prev_article = 你的模型::find()
      ->andFilterWhere([&#39;<&#39;, &#39;id&#39;, $id])
      ->andFilterWhere([其他条件)
      ->orderBy([&#39;id&#39; => SORT_DESC])
      ->limit(1)
      ->one();
    //查询下-篇文章
    $next_article = 你的模型::find()
      ->andFilterWhere([&#39;>&#39;, &#39;id&#39;, $id])
      ->andFilterWhere(其他条件)
      ->orderBy([&#39;id&#39; => SORT_ASC])
      ->limit(1)
      ->one();
 
 
    $model[&#39;prev_article&#39;] = [
      &#39;url&#39; => !is_null($prev_article) ? Url::current([&#39;id&#39;=>$prev_article->id]) : &#39;javascript:;&#39;,
      &#39;title&#39; => !is_null($prev_article) ? $prev_article->title : &#39;没有了&#39;,
    ];
 
    $model[&#39;next_article&#39;] = [
      &#39;url&#39; => !is_null($next_article) ? Url::current([&#39;id&#39;=>$next_article->id]) : &#39;javascript:;&#39;,
      &#39;title&#39; => !is_null($next_article) ? $next_article->title : &#39;没有了&#39;,
    ];
 
    return $this->render(&#39;view&#39;, 
      &#39;model&#39; => $model, 
    );
Copy after login

In view

<div class="left">
    <p>上一篇:
      <a href="<?=$model[&#39;prev_article&#39;][&#39;url&#39;]?>">
        <?=$model[&#39;prev_article&#39;][&#39;title&#39;]?>
      </a>
    </p>
  </div>
  <div class="right">
    <p>下一篇:
      <a href="<?=$model[&#39;next_article&#39;][&#39;url&#39;]?>">
        <?=$model[&#39;next_article&#39;][&#39;title&#39;]?>
      </a>
    </p>
  </div>
Copy after login

The above is the content of this article All the content, I hope it will be helpful to everyone's learning, and I also hope everyone will support the PHP Chinese website.

For more code examples of yii2 implementing the "previous article, next article" function, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template