首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Laravel Eloquent 獲取上一篇/下一篇文章的實現技巧

     編輯:PHP 綜合知識

源於 StackOverflow 問題:Laravel Eloquent 如何獲取當前記錄的下一條。此需求常見於文章上一篇/下一篇功能。Laravel 無直接方法,需巧妙實現:

核心邏輯

// 獲取上一篇文章 ID
protected function getPrevArticleId($id) {
    return Article::where('id', '<', $id)->max('id');
}

// 獲取下一篇文章 ID
protected function getNextArticleId($id) {
    return Article::where('id', '>', $id)->min('id');
}

max('id') 取比當前 ID 小的最大值(上一篇),min('id') 取比當前 ID 大的最小值(下一篇)。

應用示例

$next_article = Article::find($this->getNextArticleId($article->id));

進階:結合發布時間

給 articles 表增加 published_at(Carbon 對象),前端按此判斷是否顯示:

// Model 作用域
public function scopePublished($query) {
    $query->where('published_at', '<=', Carbon::now());
}

// Controller 查詢
$articles = Article::latest('published_at')->published()->get();

視圖顯示:

<li class="previous">
    @if($prev_article)
    <a href="/post/{{ $prev_article->slug }}" rel="prev">
        <i class="fa fa-chevron-left"></i><strong>上一篇</strong><span> {{ $prev_article->title }}</span>
    </a>
    @endif
</li>
<li class="next">
    @if($next_article && $next_article->published_at < Carbon\Carbon::now())
    <a href="/post/{{ $next_article->slug }}" rel="next">
        <i class="fa fa-chevron-right"></i><strong>下一篇</strong>
        <span> {{ $next_article->title }}</span>
    </a>
    @endif
</li>

完成文章上下篇導航功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved