簡體   English   中英

Laravel分頁在leftjoin

[英]Laravel pagination at leftjoin

我想在laravel上創建帶有分頁的leftjoin。 如何創建與leftjoin分頁?

這是我的代碼:

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
        ->select('news.*' ,'categories.category')
        ->get()->sortByDesc('created_at');

以前,我使用$news = News::paginate(10); 及其作品,但它沒有左聯接。

這是我的HTML代碼來創建分頁

{{$news->links('vendor.pagination.pagination')}}

分頁功能應在查詢生成器對象上完成,而不要在get()返回的集合上get()

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
        ->select('news.*' ,'categories.category')
        ->paginate(10);

排序也一樣。 調用get()->sortByDesc() ,您將獲得一個Collection,然后通過PHP對該Collection進行排序。 通常,您需要在查詢構建器中使用orderBy()對SQL進行排序。

$news = News::leftJoin('categories','news.category_id', '=', 'categories.id')
        ->select('news.*' ,'categories.category')
        ->orderBy('created_at', 'DESC')
        ->paginate(10);

善用口才:關系

例如:

News.php模型

class News extends Model
    {
        protected $primaryKey = 'id';

        function withCategories() {
       return $this->hasOne('App\Categories', 'id', 'category_id');
    }

    public function list(){
         News::with('withCategories')->orderBy('created_at', 'DESC')
    ->paginate(10);
    }
}

在news.blade.php中(示例)

<table>
<tbody>
@foreach ($news as $news)
<tr>
<th>{{ $news->id }}</th>
<td>{{ $news->title }}</td>
<td>{{ $news->withCategories->title }}</td> <!-- Category name-->
</tr>
@endforeach
</tbody>
</table>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM